r - 仅当另一列在 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
所以像这样
我找不到该怎么办,我该如何处理?谢谢。
编辑:更准确的数据框
解决方案
我不完全确定最后两行是从哪里来的,但这是我的看法:
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]
推荐阅读
- sql-server - 通过 Sql 服务器发送短信或在 Excel 中复制文本并从手机发送
- powershell - 列出打开的 Web URL
- javascript - reactjs中如何获取文件的文件长度
- matlab - 使用 Gurobi 运行 MIQP:如何提高时间性能?
- css - 页脚隐藏内容
- python - Tensorflow 似乎有科学记数法的问题
- java - LinkedList 或 HashSet 等类是否被视为依赖项?
- javascript - 我如何从不同的组件调用默认函数
- matlab - Matlab:按另一个需要年龄的向量对数组进行排序
- javascript - React and Bootstrap Javascript