我目前有一个类似的数据框(时间以秒为单位,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
就这样
我找不到该怎么办,我该如何处理? 谢谢。
编辑:更准确的数据框
答案 0 :(得分:2)
我不确定最后两行来自哪里,但这是我的看法:
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
要获得 last 块的总和,请使用一些data.table魔术:
setkey(df, index)
nextblocksums <- df[index!=max(index), .(index=index+1,nextBlockSum=Sum)]
df[ nextblocksums , LastBlocksSum:=i.nextBlockSum]