Tibo
Tibo

Reputation: 68

Replace missing data with NA in R

I am building a time series (xts) from several observations stored in a list of xts objects. The extracted data is missing sometimes, R report the error:

"Error in NextMethod(.Generic) : replacement has length zero"

I would like R to report NA instead. I guess the answer lies in tryCatch(), but I'm unable to nail it.

# Here is a MCVE:
Contract <- list(xts(1:12,order.by=Sys.Date()-1:12),
                 xts(1:10,order.by=Sys.Date()-1:10),
                 xts(1:8,order.by=Sys.Date()-2:9))

Vol <- xts(matrix(0, 12,3, byrow = FALSE),order.by=Sys.Date()-1:12)
for (A in 1:12){for (B in 1:3){
       Vol[A,B] <- Contract[[B]][index(Vol)[A]]
     }}
Vol

Any help would be gladly appreciated. (Also, if someone as clever idea to vectorize the double loop...)

Upvotes: 2

Views: 86

Answers (1)

jay.sf
jay.sf

Reputation: 72974

We could check if coercing the generated observation into numeric yields numeric(0).

Here is a solution with sapply() that creates the matrix out of a vector of all dates.

all.dates <- Sys.Date() - 1:12

MX <- t(sapply(seq_along(all.dates), function(x) 
  sapply(seq_along(Contract), function(y) {
    obs <- Contract[[y]][all.dates[x]]
    if (identical(as.numeric(obs), numeric(0)))  # reporting NA
      xts(NA, all.dates[x])
    else 
      obs
  }
  )))

Vol <- xts(MX, order.by=all.dates)
rm(MX)  # clean up

Result

> Vol
           [,1] [,2] [,3]
2019-01-09   12   NA   NA
2019-01-10   11   NA   NA
2019-01-11   10   10   NA
2019-01-12    9    9    8
2019-01-13    8    8    7
2019-01-14    7    7    6
2019-01-15    6    6    5
2019-01-16    5    5    4
2019-01-17    4    4    3
2019-01-18    3    3    2
2019-01-19    2    2    1
2019-01-20    1    1   NA

Could you please check if this is the result you expect?

Upvotes: 1

Related Questions