逐行累计和 [英] Rowwise cumulative sum

查看:19
本文介绍了逐行累计和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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

推荐答案

另一个选项使用 Reduceaccumulate=TRUE:

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

这篇关于逐行累计和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆