Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

r - Rowwise cumulative sum

I have a data.table dt as follows.

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

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

The desired output is as follows:

dt
   t1 t3 t7
1:  0 12 37
2:  0  5 53
3:  0  8 15
4:  0  9 18
5:  0  5 19
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another option use Reduce with 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...