[英]cumulative sum of array of rows
I have this data frame:我有这个数据框:
transaction ID![]() |
day number![]() |
Predicted value![]() |
---|---|---|
12 ![]() |
1 ![]() |
.001 ![]() |
12 ![]() |
2 ![]() |
.002 ![]() |
12 ![]() |
1 ![]() |
.001 ![]() |
12 ![]() |
2 ![]() |
.002 ![]() |
13 ![]() |
1 ![]() |
.001 ![]() |
13 ![]() |
2 ![]() |
.002 ![]() |
13 ![]() |
3 ![]() |
.002 ![]() |
13 ![]() |
4 ![]() |
.003 ![]() |
I want to take the cumulative sum of the each set of predicted values based on the sequential day numbers (ie cumsum of the first 2 rows, cumsum of the next 2, and the cumsum of the last 4)我想根据连续的天数(即前 2 行的 cumsum,下 2 行的 cumsum,以及最后 4 行的 cumsum)获取每组预测值的累积和
so the results would be.003, .003, .008所以结果将是.003, .003, .008
Using R base使用R基地
sapply(split(df$Predicted_value,cumsum(c(1,diff(df$day_number)!=1))), sum)
1 2 3
0.003 0.003 0.008
Based on your desired output, it's not a cumulative sum but a sum by transaction ID and day group.根据您想要的 output,它不是累计总和,而是按交易 ID 和日期组的总和。
Using data.table
使用
data.table
dat = data.table(transID = c(12,...),
dayNum = c(1,2,...),
predVal = c(0.001, 0.002, ...))
# introduce a grouping column; each group starts when day == 1
dat[,
gr := cumsum(dayNum == 1)]
# aggregate
dat[,
sum(predVal),
by = gr]
gr V1
1: 1 0.003
2: 2 0.003
3: 3 0.008
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.