2017-05-24 62 views
1

我有其表示随着时间的推移一堆相关矩阵的特征值的矩阵。转换矩阵回XTS

我的矩阵具有与它引用的时间列,但它不是一个时间序列或XTS,据我可以告诉对象。

最终我希望该矩阵转换成的格式是它的数据帧或XTS对象,让我随时间绘制的N个最大本征值。

我怎么能转换这个矩阵成这样的格式,我想XTS是可取的,因为它是一个时间序列的代表性?

我曾尝试以下,但我不能得到它的工作:

time.index <- as.POSIXct(colnames(eigen)) 
eigenXTS <- as.xts(eigen, order.by = time.index) 

,但我回到指

Error in xts(x, order.by = order.by, frequency = frequency, ...) : 
    NROW(x) must match length(order.by) 

我的数据看起来如下错误:

> class(eigen) 
[1] "matrix" 

> str(eigen) 
num [1:12, 1:1334] 4.461 2.292 2.216 1.425 0.839 ... 
- attr(*, "dimnames")=List of 2 
    ..$ : NULL 
    ..$ : chr [1:1334] "2017-01-20 18:45:00" "2017-01-20 19:00:00" "2017-01-20 19:15:00" "2017-01-20 19:30:00" ... 

> dim(eigen) 
[1] 12 1334 

> eigen[1:4,1:4] 
    2017-01-20 18:45:00 2017-01-20 19:00:00 2017-01-20 19:15:00 2017-01-20 19:30:00 
[1,]   4.461059   4.774866   4.658013   4.841987 
[2,]   2.291520   2.330239   2.101630   2.145122 
[3,]   2.215749   2.183941   1.935904   1.861954 
[4,]   1.424662   1.277794   1.750168   1.762004 

任何人都可以点我如何最好的方法解决这个问题的方向是什么?

回答

1

as.xts预计矩阵的rownames是时间戳。在你的情况下,eigencolnames包含时间戳。因此,你需要在调用as.xts前转eigen

xeigen <- as.xts(t(eigen)) 
xeigen 
#       [,1]  [,2]  [,3]  [,4] 
# 2017-01-20 18:45:00 4.461059 2.291520 2.215749 1.424662 
# 2017-01-20 19:00:00 4.774866 2.330239 2.183941 1.277794 
# 2017-01-20 19:15:00 4.658013 2.101630 1.935904 1.750168 
# 2017-01-20 19:30:00 4.841987 2.145122 1.861954 1.762004 

由于xts对象只是一个具有时间索引的矩阵,因此不需要强制将矩阵转换为data.frame。这样做意味着as.xts将不得不将其强制回矩阵。

1

我认为你需要转置矩阵并将其转换为xts所以你可以有行作为记录(观察)和列变量之前转换为data.frame

> dput(eigen) 
structure(list(`2017-01-20 18:45:00` = c("4.461059", "2.291520", 
"2.215749", "1.424662"), `2017-01-20 19:00:00` = c("4.774866", 
"2.330239", "2.183941", "1.277794"), `2017-01-20 19:15:00` = c("4.658013", 
"2.101630", "1.935904", "1.750168"), `2017-01-20 19:30:00` = c("4.841987", 
"2.145122", "1.861954", "1.762004")), .Names = c("2017-01-20 18:45:00", 
"2017-01-20 19:00:00", "2017-01-20 19:15:00", "2017-01-20 19:30:00" 
), row.names = c(NA, 4L), class = "data.frame") 

> eigen <- as.data.frame(t(eigen)) 
          V1  V2  V3  V4 
2017-01-20 18:45:00 4.461059 2.291520 2.215749 1.424662 
2017-01-20 19:00:00 4.774866 2.330239 2.183941 1.277794 
2017-01-20 19:15:00 4.658013 2.101630 1.935904 1.750168 
2017-01-20 19:30:00 4.841987 2.145122 1.861954 1.762004 

> xts_eigen <- xts::xts(eigen,order.by = as.POSIXct(rownames(eigen))) 
          V1  V2  V3  V4 
2017-01-20 18:45:00 4.461059 2.291520 2.215749 1.424662 
2017-01-20 19:00:00 4.774866 2.330239 2.183941 1.277794 
2017-01-20 19:15:00 4.658013 2.101630 1.935904 1.750168 
2017-01-20 19:30:00 4.841987 2.145122 1.861954 1.762004 

> class(xts_eigen) 
[1] "xts" "zoo"