首页 > 解决方案 > 对来自雅虎的 xts 数据应用延迟不起作用

问题描述

我正在尝试对 xts 数据应用延迟,但由于某种原因它不想工作!

library(quantmod)
mystock <- c("GOOG")
getSymbols(mystock, src = "yahoo", from = "2020-01-01", to = "2021-01-01")
Google <- (GOOG)

Google <- subset(GOOG, select = GOOG.Adjusted)

googlets <- ts(Google)
head(googlets)

window5 <- data.frame(x5=Lag(googlets,5), x4=Lag(googlets,4), x3=Lag(googlets,3), 
                      x2=Lag(googlets,2), x1=Lag(googlets,1), googlets)
names(window5) <- c('x5','x4','x3', 'x2', 'x1', 'x')
window5

我可以在转换为 ts 之前对数据应用滞后。结果显示每一行都有一个非滞后数字。

有人能指点我一个方向吗

标签: rlag

解决方案


使用cbind作品!

window5 <- cbind(x5=Lag(googlets,5), x4=Lag(googlets,4), x3=Lag(googlets,3), 
                 x2=Lag(googlets,2), x1=Lag(googlets,1), googlets)
colnames(window5) <- c('x5','x4','x3', 'x2', 'x1', 'x')
head(window5)
#           x5      x4      x3      x2      x1       x
# [1,] 1367.37      NA      NA      NA      NA      NA
# [2,] 1360.66 1367.37      NA      NA      NA      NA
# [3,] 1394.21 1360.66 1367.37      NA      NA      NA
# [4,] 1393.34 1394.21 1360.66 1367.37      NA      NA
# [5,] 1404.32 1393.34 1394.21 1360.66 1367.37      NA
# [6,] 1419.83 1404.32 1393.34 1394.21 1360.66 1367.37

推荐阅读