Sum of most recent values across groups

前端 未结 3 1237
日久生厌
日久生厌 2021-01-31 03:22

For each row of my data I\'d like to compute the sum of most recent value for each group:

dt = data.table(group = c(\'a\',\'b\',\'a\',\         


        
3条回答
  •  深忆病人
    2021-01-31 04:01

    I would create a column for each group showing the latest value for that group. Then just sum those columns:

    library(zoo)
    result <- rep(0, nrow(dt))
    for(g in dt[, unique(group)]) {
      result <- result + dt[, na.fill(na.locf(ifelse(group==g, 1, NA)*value, na.rm=F), 0)]
    }
    
    all(dt[, desired] == result)
    

提交回复
热议问题