我有一个时间序列的数据框:
X1.HK.Equity X X2.HK.Equity X.2 X3.HK.Equity X.4
1 31/12/2002 38.855 31/12/2002 19.547 31/12/2002 5.011
2 02/01/2003 38.664 02/01/2003 19.547 02/01/2003 4.986
3 03/01/2003 40.386 03/01/2003 19.547 03/01/2003 4.962
4 06/01/2003 40.386 06/01/2003 19.609 06/01/2003 4.937
5 07/01/2003 40.195 07/01/2003 19.609 07/01/2003 4.937
6 08/01/2003 40.386 08/01/2003 19.547 08/01/2003 4.912
我想拍摄这个时间序列并将其更改为3个项目的列表,每个项目都是从1-2,3-4和5-6列创建的XTS。请注意,时间序列不一定具有相同的日期。
如果有人可以使用plyr
库告诉我如何执行此操作,我会非常高兴。
dput
:
structure(list(X1.HK.Equity = c("31/12/2002", "02/01/2003", "03/01/2003",
"06/01/2003", "07/01/2003", "08/01/2003"), X = c(38.855, 38.664,
40.386, 40.386, 40.195, 40.386), X2.HK.Equity = c("31/12/2002",
"02/01/2003", "03/01/2003", "06/01/2003", "07/01/2003", "08/01/2003"
), X.2 = c(19.547, 19.547, 19.547, 19.609, 19.609, 19.547), X3.HK.Equity = c("31/12/2002",
"02/01/2003", "03/01/2003", "06/01/2003", "07/01/2003", "08/01/2003"
), X.4 = c(5.011, 4.986, 4.962, 4.937, 4.937, 4.912)), .Names = c("X1.HK.Equity",
"X", "X2.HK.Equity", "X.2", "X3.HK.Equity", "X.4"), row.names = c(NA,
6L), class = "data.frame")
答案 0 :(得分:2)
一个普通的lapply
可以在这里工作:
to.xts <- function(i) as.xts(read.zoo(DF[i+0:1], format = "%d/%m/%Y"))
lapply(seq(1, ncol(DF), 2), to.xts)
如果这不仅仅是一个例子,事实上,只有三个系列就足以用最后一行代替:
list(to.xts(1), to.xts(3), to.xts(5))
答案 1 :(得分:1)
我不知道这是否是最有效的方法,但希望这是合乎逻辑的。
library(xts)
lapply(seq_along(mydf[c(FALSE, TRUE)]), function(x) {
xts(mydf[c(FALSE, TRUE)][x],
order.by=as.Date(mydf[c(TRUE, FALSE)][, x], format = "%d/%m/%Y"))
})
# [[1]]
# X
# 2002-12-31 38.855
# 2003-01-02 38.664
# 2003-01-03 40.386
# 2003-01-06 40.386
# 2003-01-07 40.195
# 2003-01-08 40.386
#
# [[2]]
# X.2
# 2002-12-31 19.547
# 2003-01-02 19.547
# 2003-01-03 19.547
# 2003-01-06 19.609
# 2003-01-07 19.609
# 2003-01-08 19.547
#
# [[3]]
# X.4
# 2002-12-31 5.011
# 2003-01-02 4.986
# 2003-01-03 4.962
# 2003-01-06 4.937
# 2003-01-07 4.937
# 2003-01-08 4.912
基本上,它使用TRUE
和FALSE
的回收来选择备用列。 seq_along
部分告诉我们有多少对(在本例中为3),在匿名函数中,我们使用c(FALSE, TRUE)
对值进行分组,并使用c(TRUE, FALSE)
对日期进行分组。 / p>
答案 2 :(得分:1)
使用plyr,使用llply
tss = llply(c(1,3,5),function(s){ts=mydf[,s:(s+1)];xts(ts[,2],order.by=as.Date(ts[,1],format="%d/%m/%Y"))} )
给你
> tss[[1]]
[,1]
2002-12-31 38.855
2003-01-02 38.664
2003-01-03 40.386
2003-01-06 40.386
2003-01-07 40.195
2003-01-08 40.386
> class(tss[[1]])
[1] "xts" "zoo"
>
1,3,5向量通常是seq(1,ncol(mydf),by=2)