Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R时间序列相交-ts对象列表_R_Time Series - Fatal编程技术网

R时间序列相交-ts对象列表

R时间序列相交-ts对象列表,r,time-series,R,Time Series,我有一个包含多个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 n

我有一个包含多个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))
,但同样无效。

您可以使用
Reduce

b <- Reduce(ts.intersect, List1)
# this is similar to ts.intersect(ts.intersect(List1[[1]],List1[[2]]), List1[3]])

您也可以在此处使用
do.call

b <- do.call(ts.intersect, List1)
# this is similar to ts.intersect(List1[[1]], List1[[2]], List1[3]])

在这两种情况下,您都可以使用以下命令更改名称:

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

colnames(b)zoo具有多路合并功能,因此转换为zoo合并并转换回:

> 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
>图书馆(动物园)
>list2as.ts(do.call(“merge”,Map(as.zoo,c(List2,all=FALSE)))
a1 a2 a3
2002年1月-1.2037687 1.5758712 1.2852462
2002年2月-0.5020486 0.2406350 0.4942195
2002年3月-1.3920381-0.7291974-0.1902032
2002年4月-0.9053585 0.2381535 1.6644473
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
> 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