table中两列的总和

table中两列的总和

本文介绍了R-data.table中两列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.table如下-

I have a data.table as follows -

dt = data.table(
  date = seq(as.Date("2015-12-01"), as.Date("2015-12-10"), by="days"),
  v1 = c(seq(1, 9), 20),
  v2 = c(5, rep(NA, 9))
)
dt
          date v1 v2
 1: 2015-12-01  1  5
 2: 2015-12-02  2 NA
 3: 2015-12-03  3 NA
 4: 2015-12-04  4 NA
 5: 2015-12-05  5 NA
 6: 2015-12-06  6 NA
 7: 2015-12-07  7 NA
 8: 2015-12-08  8 NA
 9: 2015-12-09  9 NA
10: 2015-12-10 20 NA

问题1:我想将v1的当前行值与v2的前一行值相加,以便输出如下所示.

Question 1: I want to add the current row value of v1 with the previous row value of v2 so the output looks like the following.

          date v1 v2
 1: 2015-12-01  1  5
 2: 2015-12-02  2  7
 3: 2015-12-03  3 10
 4: 2015-12-04  4 14
 5: 2015-12-05  5 19
 6: 2015-12-06  6 25
 7: 2015-12-07  7 32
 8: 2015-12-08  8 40
 9: 2015-12-09  9 49
10: 2015-12-10 20 69

我尝试使用rollapplyr函数来实现此目的,但是失败了.

I have tried to use rollapplyr function to achieve this but failed.

问题2:与其将其添加(如问题1中的方法一样),我不希望将函数qma滚动应用于v1的当前行值和v2的前一行值 qma<-函数(x,y){(x + y + 7)/2}

Question 2: Instead of adding (as in Question 1), I want to roll apply the function qma to the current row value of v1 with the previous row value of v2qma <- function(x, y){(x+y+7)/2}

我确信必须有一种简单的方法可以使用data.table在一行中完成此操作.

I am sure there must be a simple way to do this in one line using data.table.

谢谢

推荐答案

您可以将 first v2 值添加到 v1 的累积总和中.

You can add first v2 value to cumulative sum of v1.

library(data.table)
dt[, v2:= first(v2) + c(0, cumsum(v1[-1]))]
dt

#          date v1 v2
# 1: 2015-12-01  1  5
# 2: 2015-12-02  2  7
# 3: 2015-12-03  3 10
# 4: 2015-12-04  4 14
# 5: 2015-12-05  5 19
# 6: 2015-12-06  6 25
# 7: 2015-12-07  7 32
# 8: 2015-12-08  8 40
# 9: 2015-12-09  9 49
#10: 2015-12-10 10 59

这篇关于R-data.table中两列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:17