1

我有一个时间序列的数据框:

  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")
4

3 回答 3

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))
于 2013-04-07T11:03:03.680 回答
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

基本上,它使用回收TRUEFALSE选择备用列。该seq_along部分告诉我们有多少对(在本例中为 3),并且在匿名函数中,我们使用 对值进行子集化,使用c(FALSE, TRUE)对日期进行子集化c(TRUE, FALSE)

于 2013-04-07T08:32:25.207 回答
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)

于 2013-04-07T10:40:40.483 回答