ts.intersect 不适用于 xts 对象

ts.intersect does not work with xts objects

以下会产生错误

a1 = as.xts(ts(rnorm(20), start=c(1980,1), freq=4))
a2 = as.xts(ts(rnorm(30), start=c(1983,1), freq=4))
a = ts.intersect(a1,a2)

Error in .cbind.ts(list(...), .makeNamesTs(...), dframe = dframe, union = FALSE) : 
  no time series supplied

文档说参数应该是

两个或多个单变量或多变量时间序列,或可以强制转换为时间序列的对象。

ts.intersect 通过查找 tsp 属性来确定对象是否为 ts 对象。 as.xts.ts 删除了 tsp 属性,这就是为什么它不会被强制返回到 ts 对象。

这看起来像是 xts->ts->xts 转换中的错误,但我需要仔细查看。

作为变通方法,您可以手动将 tsp 属性添加到您的 xts 对象(请注意,这可能会导致其他 xts 方法出现问题,例如 str.xts)并添加一个 .tsp 属性也是如此。

set.seed(21)
A1 <- ts(rnorm(20), start=c(1980,1), freq=4)
A2 <- ts(rnorm(30), start=c(1983,1), freq=4)
# convert to xts
a1 <- as.xts(A1)
a2 <- as.xts(A2)
# add tsp attribute
# (so stats:::.cbind.ts will think these are coercible to ts objects)
tsp(a1) <- tsp(A1)
tsp(a2) <- tsp(A2)
# add .tsp attribute
# (needed for as.ts.xts to work)
attr(a1,'.tsp') <- tsp(A1)
attr(a2,'.tsp') <- tsp(A2)

a <- ts.intersect(a1,a2)