如何使用xts从列表中按日期查找值

问题描述 投票:0回答:2

我有一个xts world列表

list

$`XX`
            return
2018-01-31  2.16
2018-02-28  2.06
2018-03-31  2.12
2018-04-30  2.41
2018-05-31  2.07
$`YY`
            return
2018-01-31  1.12
2018-02-28  0.06
2018-03-31  3.12
$`ZZ`
            return
2018-01-31  3.15
2018-02-28  1.03
2018-03-31  0.11
2018-04-30  1.42
2018-05-31  2.04 

我需要制作一个这样的矩阵

m_2018_05_31

     return
[1,] 2.07
[2,] NA
[3,] 2.04

我使用了这个,但由于YY中没有值,所以出现了错误

m_2018_05_31 <- matrix(1:3)
for(t in 1:3) {
m_2018_05_31[t,]<-list[[t]]$return["2018-05-31"]
}
r list xts
2个回答
0
投票

如果列出了名为xtsdata对象,则可以使用coredataindex功能。

library(zoo)

sapply(data, function(x) {
   inds <- index(x) == as.Date('2018-05-31')
   if(any(inds)) coredata(x)[inds] else NA
})

#  XX   YY   ZZ 
#2.07   NA 2.04 

1
投票

这里是利用merge功能的另一种选择:

d <- "2018-05-31"
do.call(rbind, lapply(list(X, Y), function(x) merge(x, as.Date(d), fill=NA)[d]))

输出:

              x
2018-05-31   NA
2018-05-31 2.07

数据:

X=as.xts(read.zoo(text="
2018-01-31 2.16
2018-02-28 2.06"))

Y=as.xts(read.zoo(text="
2018-03-31 2.12
2018-04-30 2.41
2018-05-31 2.07"))
© www.soinside.com 2019 - 2024. All rights reserved.