行累积总和 [英] Rowwise cumulative sum
本文介绍了行累积总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 data.table
dt
如下。
df <- data.frame(t1 = rep(0,5), t3 = c(12, 5, 8,9, 5), t7= c(25, 48, 7, 9, 14))
dt <- setDT(df)
dt
t1 t3 t7
1: 0 12 25
2: 0 5 48
3: 0 8 7
4: 0 9 9
5: 0 5 14
我想获取各列的累计和。我只是把它跨行。如何在 data.table
中做到这一点。
I want to get the cumulative sums across the columns. I am only getting it across the rows. How to do this in data.table
.
dt[, 1:3 := cumsum(dt)]
dt
t1 t3 t7
1: 0 12 25
2: 0 17 73
3: 0 25 80
4: 0 34 89
5: 0 39 103
所需的输出为
dt
t1 t3 t7
1: 0 12 37
2: 0 5 53
3: 0 8 15
4: 0 9 18
5: 0 5 19
推荐答案
另一个选项使用 Reduce
和 accumulate = TRUE
:
dt[, names(dt) := Reduce(`+`, dt, accumulate = TRUE)]
dt
# t1 t3 t7
#1: 0 12 37
#2: 0 5 53
#3: 0 8 15
#4: 0 9 18
#5: 0 5 19
这篇关于行累积总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文