使用 2 个向量参数滚动函数 [英] Rolling over function with 2 vector arguments
问题描述
我想在需要 2 个向量参数的函数上应用滚动.这是使用 data.table 的示例(不起作用):
I want to apply rolling on the function that requires 2 vector arguments. Here is the exmample (that doesn't work) using data.table:
library(data.table)
df <- as.data.table(cbind.data.frame(x=1:100, y=101:200))
my_sum <- function(x, y) {
x <- log(x)
y <- x * y
return(x + y)
}
roll_df <- frollapply(df, 10, function(x, y) {
my_sum(x, y)})
它无法识别 y 列.Ofc,解决方案可以是使用 xts 或其他一些包.
It doesn't recognize y column. Ofc, the solution can be using xts or some other package.
这是我要应用的真正功能:
This is the real function I want to apply:
library(dpseg)
dpseg_roll <- function(time, price) {
p <- estimateP(x=time, y=price, plot=FALSE)
segs <- dpseg(time, price, jumps=jumps, P=p, type=type, store.matrix=TRUE)
slope_last <- segs$segments$slope[length(segs$segments$slope)]
return(slope_last)
}
推荐答案
使用 runner 你可以在滚动窗口中应用任何功能.也可以在插入到 x
参数的 data.frame 行上创建运行窗口.让我们专注于更简单的函数 my_sum
.runner 中的参数 f
只能接受一个对象(在这种情况下为 data
).我鼓励将 browser()
放在函数中以逐行调试,然后再对子集应用一些奇特的模型(某些算法需要最少的观察次数).
With runner you can apply any function in rolling window. Running window can be created also on a rows of data.frame inserted to x
argument. Let's focus on simpler function my_sum
. Argument f
in runner can accept only one object (data
in this case). I encourage to put browser()
to the function to debug row-by-row before you apply some fancy model on the subset (some algorithms requires some minimal number of observations).
my_sum <- function(data) {
# browser()
x <- log(data$x)
y <- x * data$y
tail(x + y, 1) # return only one value
}
my_sum
应该只返回一个值,因为 runner
为每一行计算 - 如果 my_sum
返回向量,你会得到一个列表.因为 runner 是一个独立的函数,所以你需要将 data.table 对象传递给 x
.最好的方法是使用 x = .SD
(参见 这里为什么)
my_sum
should return only one value, because runner
computes for each row - if my_sum
returns vector, you would get a list.
Because runner is an independent function you need to pass data.table object to x
. Best way to do this is to use x = .SD
(see here why)
df[,
new_col := runner(
x = .SD,
f = my_sum,
k = 10
)]
这篇关于使用 2 个向量参数滚动函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!