我正在尝试使用 lag
在 xts 对象中创建滞后向量功能。它在使用 $
在 xts 对象中定义新向量时起作用。符号(例如 x.ts$r1_lag
),但在使用方括号定义新变量时会这样做,即 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"])
我需要使用
[]
符号而不是 $
引用向量的符号,因为如果我想对多个 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)
}
}
谢谢!
最佳答案
你不需要使用 [<-.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)
}
}
关于r - 使用 $ vs. [] 符号创建 xts 对象的滞后变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30919160/