lrc*_*ark 4 r nested-lists xts
我试图使用该lag函数在xts对象中创建一个滞后向量.它在使用$符号(例如x.ts$r1_lag)在xts对象中定义新向量时起作用,但在使用方括号定义新变量时也是如此,即xts[,"r1_lag"].见下面的代码:
library(xts)
x <- data.frame(date=seq(as.Date('2015-01-01'), by='days', length=100),
runif(1e2), runif(1e2), runif(1e2))
colnames(x) <- c("date", "r1", "r2", "r3")
#the following command works
x.ts <- xts(x, order.by=x$date)
x.ts$r1_lag <- lag(x.ts$r1)
# but the following does not (says subscript is out of bounds)
x.ts <- xts(x, order.by=x$date)
x.ts[,"r1_lag"] <- lag(x.ts[,"r1"])
Run Code Online (Sandbox Code Playgroud)
我需要使用[]符号而不是$符号来引用向量,因为如果我想对多个xts对象中的向量运行滞后变换(多个xts对象列表中的向量),我无法在其中定义新向量使用$符号的对象,即我不能使用下面的程式化循环中的符号来定义新的向量:
for (i in letters) {
for (j in variables) {
macro.set.ts$i$paste(j,"_L1",sep="") <- lag(macro.set.ts[[i]][,j])
macro.set.ts$i$paste(j,"_L2",sep="") <- lag(macro.set.ts[[i]][,j], 2)
macro.set.ts$i$paste(j,"_L4",sep="") <- lag(macro.set.ts[[i]][,j], 4)
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
你不需要使用[<-.xts.你可以merge改用:
for (i in letters) {
for (j in variables) {
# create all lags
mst_ij <- macro.set.ts[[i]][,j]
jL <- merge(lag(mst_ij), lag(mst_ij, 2), lag(mst_ij, 4))
colnames(jL) <- paste(j, c("L1","L2","L4"), sep="_")
# merge back with original data
macro.set.ts[[i]] <- merge(macro.set.ts[[i]], jL)
}
}
Run Code Online (Sandbox Code Playgroud)