【问题标题】:Replace last value in group with corresponding value in other column将组中的最后一个值替换为其他列中的相应值
【发布时间】:2018-03-30 20:40:50
【问题描述】:

使用分组数据时,我想更改一列中的最后一个条目以匹配另一列中该组的相应值。因此,对于我下面的数据,对于每个“巢”(组),最后一个“状态”条目将等于该巢的“命运”。

这样的数据:

 nest   Status   fate
   1      1       2
   1      1       2
   2      1       3
   2      1       3
   2      1       3

想要的结果:

 nest   Status   fate
   1      1       2
   1      2       2
   2      1       3
   2      1       3
   2      3       3

应该就是这么简单。我从dplyr and tail to change last value in a group_by in r 尝试了以下内容;它适用于某些群体,但在其他群体中,它替代了错误的“命运”值:

 library(data.table)
 indx <- setDT(df)[, .I[.N], by = .(nest)]$V1
 df[indx, Status := df$fate]

尝试这种方法时遇到各种错误dplyr mutate/replace on a subset of rows

 mutate_last <- function(.data, ...) {
   n <- n_groups(.data)
   indices <- attr(.data, "indices")[[n]] + 1
   .data[indices, ] <- .data[indices, ] %>% mutate(...)
   .data
 }

 df <- df %>%
  group_by(nest) %>%
  mutate_last(df, Status == fate)

我一定是从上面提到的资源中遗漏了一些简单的东西吗?

【问题讨论】:

  • 猜猜data.table 尝试的最后一行应该是df[indx, Status := fate]。也可以试试df[,Status:=c(Status[-.N],fate[.N]),by=nest]

标签: r


【解决方案1】:

有点像

library(tidyverse)

df <- data.frame(nest = c(1,1,2,2,2),
                 status = rep(1, 5),
                 fate = c(2,2,3,3,3))
df %>% 
   group_by(nest) %>% 
   mutate(status = c(status[-n()], tail(fate,1)))

【讨论】:

    【解决方案2】:

    不确定这是否绝对是最好的方法,但这是一个非常简单的解决方案:

    library(dplyr)
    dat <- data.frame(nest = c(1,1,2,2,2),
                      Status = c(1,1,1,1,1),
                      fate = c(2,2,3,3,3))
    
    dat %>%
      arrange(nest, Status, fate) %>% #enforce order
      group_by(nest) %>%
      mutate(Status = ifelse(is.na(lead(nest)), fate, Status))
    

    E:做了一个快速的改变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 2020-08-07
      • 2021-09-27
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多