与data.table的滚动关联 [英] Rolling correlation with data.table
本文介绍了与data.table的滚动关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在两个 data.table
列之间进行滚动关联。
I'm trying to do a rolling correlation between two data.table
columns.
dt <- data.table(a=-1:10,b=1:12)
> dt
a b
1: -1 1
2: 0 2
3: 1 3
4: 2 4
5: 3 5
6: 4 6
7: 5 7
8: 6 8
9: 7 9
10: 8 10
11: 9 11
12: 10 12
这是我尝试使用 rollapply
来自 zoo
:
library(zoo)
dt[,rcor:=rollapplyr(as.list(a,b),width=5,
FUN=function(y) {return(cor(y[[1]],y[[2]]))},fill=NA)]
Error in zoo(data) : "x" : attempt to define invalid zoo object
并与 roll
中的 roll_cor
:
library(roll)
roll_cor(dt[,.(a,b)],5)
Error in roll_cor(dt[, .(a, b)], 5) :
Not compatible with requested type: [type=list; target=double].
推荐答案
尝试一下:
corr <- function(y) cor(y[, 1], y[, 2])
dt[,rcor:=rollapplyr(.SD, 5, corr, by.column = FALSE, fill = NA)]
这篇关于与data.table的滚动关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文