0

I have a list with 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 

I need to make a matrix like this

m_2018_05_31

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

I used this and I got an error because there is not value in YY

m_2018_05_31 <- matrix(1:3)
for(t in 1:3) {
m_2018_05_31[t,]<-list[[t]]$return["2018-05-31"]
}
Angelo
  • 41
  • 4

2 Answers2

1

Here is another option leveraging the merge capability of :

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

output:

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

data:

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"))
chinsoon12
  • 25,005
  • 4
  • 25
  • 35
0

If you list of xts object called data you can use coredata and index function.

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 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213