尝试滞后 xts 时间序列时出现零长度错误?

Mic*_*elE 2 r xts

我使用以下命令生成了基本的 xts 对象。

library(quantmod)
temp1 <- getSymbols("GOOG",src = 'yahoo',from=Sys.Date()-50,to = Sys.Date(),auto.assign=FALSE)
temp2 <- temp1$GOOG.Close
head(temp2)
           GOOG.Close
2020-05-20    1406.72
2020-05-21    1402.80
2020-05-22    1410.42
2020-05-26    1417.02
2020-05-27    1417.84
2020-05-28    1416.73
lag(temp2,1)
Error in c.xts(NA_real_, c(1406.719971, 1402.800049, 1410.420044, 1417.02002,  : 
  zero-length vectors with non-zero-length index are not allowed
Run Code Online (Sandbox Code Playgroud)

据我所知 temp2 的长度不为零,所以我不明白这个错误。

同样, diff(temp2) 函数确实按预期工作。

这似乎是我最近更新到 R 4.0.1 时开始的

考虑到我确实有一个非零向量,我找不到对此错误的任何解释。

Jos*_*ich 6

dplyr偶然加载了吗?这是我复制你的错误的唯一方法。

dplyr屏蔽stats::lag()基 R 附带的通用函数。这会中断定义方法的所有 S3 类的方法分派lag()。所以这意味着lag()可能适用于这些课程,也可能不适用于这些课程。

R> head(lag(temp2, 1))
           GOOG.Close
2020-05-26         NA
2020-05-27    1417.02
2020-05-28    1417.84
2020-05-29    1416.73
2020-06-01    1428.92
2020-06-02    1431.82
R> suppressPackageStartupMessages(library(dplyr))
R> head(lag(temp2, 1))
Error in c.xts(NA_real_, c(1417.02002, 1417.839966, 1416.72998, 1428.920044,  : 
  zero-length vectors with non-zero-length index are not allowed
Run Code Online (Sandbox Code Playgroud)

因此,您要么需要:1)不加载 dplyr,要么 2)显式调用stats::lag()您不想使用的任何地方dplyr::lag()