首页 > 解决方案 > 仅当另一列在 R 中具有良好值时,列的连续总和

问题描述

我目前有一个看起来像这样的数据框(时间以秒为单位,Zone1 为布尔值):

Time Zone1
   1     0
   3     0
   4     1
   5     1
   6     1
   7     0
   9     1
   10    1

我想获得连续标准的值总和,所以我会得到这样的结果:

Time Zone1 TimeInZone
   1     0         NA
   3     0         NA
   4     1          2
   5     1          2
   6     1          2
   7     0         NA
   9     1          1
   10    1          1

所以像这样

我找不到该怎么办,我该如何处理?谢谢。

编辑:更准确的数据框

标签: rsum

解决方案


我不完全确定最后两行是从哪里来的,但这是我的看法:

library(data.table)
df <- data.table(Value=c(3,4,1,1,2), Criteria=c(1,1,2,1,3))
# First, generate a logical vector that indicates if the criterium changed:
df[, changed:=c(TRUE, Criteria[-1] != Criteria[-length(Criteria)])]
# Then, calculate the cumulative sum to get an index:
df[, index:=cumsum(changed)]
# Calculate the sum for each level of index:
df[, Sum:=sum(Value), by=index]
# print everything:
print(df)

结果:

   Value Criteria changed index Sum
1:     3        1    TRUE     1   7
2:     4        1   FALSE     1   7
3:     1        2    TRUE     2   1
4:     1        1    TRUE     3   1
5:     2        3    TRUE     4   2

要获得最后一个块的总和,请使用一些 data.table 魔术:

setkey(df, index)
nextblocksums <- df[index!=max(index), .(index=index+1,nextBlockSum=Sum)]
df[ nextblocksums , LastBlocksSum:=i.nextBlockSum]

推荐阅读