我有一个包含多个ts对象的列表,并希望得到一个mts对象,它们是它们的交集(按时间)。
我尝试了ts.intersect(MyList)
,但这不起作用。这是一个例子:
a1 = ts(rnorm(40), start=c(2001,1), freq=12)
a2 = ts(rnorm(15), start=c(2002,1), freq=12)
a3 = ts(rnorm(40), start=c(1999,1), freq=12)
List1 = list(a1,a2,a3)
# Does not work
b = ts.intersect(List1)
# This does work, but does not use the list object
b = ts.intersect(a1,a2,a3)
我也尝试了ts.intersect(unlist(List1, recursive=FALSE))
,但也无效。
答案 0 :(得分:1)
您可以使用Reduce
:
b <- Reduce(ts.intersect, List1)
# this is similar to ts.intersect(ts.intersect(List1[[1]],List1[[2]]), List1[3]])
结果:
init.init init.x[[i]] x[[i]]
Jan 2002 -0.3300873 0.1176911 1.7521511
Feb 2002 -0.1884980 1.3868065 -0.3621873
Mar 2002 -0.3318633 0.3086265 -0.2559493
Apr 2002 -1.1453912 -0.2793208 -1.0970463
您也可以在此处使用do.call
:
b <- do.call(ts.intersect, List1)
# this is similar to ts.intersect(List1[[1]], List1[[2]], List1[3]])
但请注意,这些名字很长:
structure(c(-1.80813067709511, -1.20282170077381, 0.138045873245257,
Jan 2002 -0.3300873
Feb 2002 -0.1884980
Mar 2002 -0.3318633
Apr 2002 -1.1453912
structure(c(0.117691115312119, 1.38680649563793, 0.308626529949489,
Jan 2002 0.1176911
Feb 2002 1.3868065
Mar 2002 0.3086265
Apr 2002 -0.2793208
structure(c(-0.639791317273505, 2.40288059297931, -1.15812150063018,
Jan 2002 1.7521511
Feb 2002 -0.3621873
Mar 2002 -0.2559493
Apr 2002 -1.0970463
在这两种情况下,您都可以使用以下命令更改名称:
colnames(b) <- c("a1", "a2", "a3")
a1 a2 a3
Jan 2002 -0.3300873 0.1176911 1.7521511
Feb 2002 -0.1884980 1.3868065 -0.3621873
Mar 2002 -0.3318633 0.3086265 -0.2559493
Apr 2002 -1.1453912 -0.2793208 -1.0970463
答案 1 :(得分:1)
zoo有一个多向合并,所以转换为zoo merge并转换回来:
> library(zoo)
> List2 <- setNames(List1, c("a1", "a2", "a3"))
> as.ts(do.call("merge", Map(as.zoo, c(List2, all = FALSE))))
a1 a2 a3
Jan 2002 -1.2037687 1.5758712 1.2852462
Feb 2002 -0.5020486 0.2406350 0.4942195
Mar 2002 -1.3920381 -0.7291974 -0.1902032
Apr 2002 -0.9053585 0.2381535 1.6644473