在data.table的两列上滚动功能 [英] Rolling a function on two columns in data.table
问题描述
我有一个data.table如下-
I have a data.table as follows -
library(data.table)
dt = data.table(
date = seq(as.Date("2015-12-01"), as.Date("2015-12-10"), by="days"),
v1 = seq(1, 10),
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 10 NA
我想将函数qma应用于v1的当前行值和v2的前一行值 qma<-函数(x,y){(x + y + 7)/2}
I want to roll apply the function qma to the current row value of v1 and the previous row value of v2
qma <- function(x, y){(x+y+7)/2}
我确信必须使用Zoo :: rollapplyr或data.table在一行中完成此操作.
I am sure there must be a simple way to do this in one line using zoo::rollapplyr or data.table.
这是原始问题的后续问题, R-data.table中两列的滚动总和
This is a follow-up question of the original one here R - Rolling sum of two columns in data.table
推荐答案
对于这种递归计算,您可以在此处使用 Reduce
:
For such recursive calculation you may use Reduce
here :
library(data.table)
dt[, v2 := Reduce(qma, v1[-1], init = first(v2), accumulate = TRUE)]
dt
# date v1 v2
# 1: 2015-12-01 1 5.00000
# 2: 2015-12-02 2 7.00000
# 3: 2015-12-03 3 8.50000
# 4: 2015-12-04 4 9.75000
# 5: 2015-12-05 5 10.87500
# 6: 2015-12-06 6 11.93750
# 7: 2015-12-07 7 12.96875
# 8: 2015-12-08 8 13.98438
# 9: 2015-12-09 9 14.99219
#10: 2015-12-10 10 15.99609
Reduce
与 accumulate = TRUE
一起使用时,将执行递归计算输出,该输出取决于先前的输出.
Reduce
when used with accumulate = TRUE
performs recursive calculation output of which is dependent on previous output.
举一个简单的示例来计算累计和.
Take a simple example of calculating cumulative sum.
x <- 1:10
res <- Reduce(`+`, x, accumulate = TRUE)
res
#[1] 1 3 6 10 15 21 28 36 45 55
res [1]
是 x [1]
, res [2]
是 res [1] + x [2]
, res [3]
是 res [2] + x [3]
等.
这篇关于在data.table的两列上滚动功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!