R backlog of missing data

Is there a delay option somewhere that keeps the NS in position? I want to calculate price data where data may be missing.

Col 1 - price data Col 2 - price lag Col 3 shows p - lag (p) - the return from 99 to 104 is actually skipped, so the path length of the calculated returns will be different from the truth. Col 4 shows the delay with the saved position NA Col 5 shows a new difference - now return 5 is available for 2009-11-07

Cheers, Dave

x <- xts(c(100, 101, 97, 95, 99, NA, 104, 103, 103, 100), as.Date("2009-11-01") + 0:9)

# fake the lag I want, with NA kept in position
x.pos.lag <- lag.xts(x.pos)
x.pos.lag <- lag.xts(x.pos)
x.pos.lag['2009-11-07']=99
x.pos.lag['2009-11-06']=NA

cbind(x, lag.xts(x), x - lag.xts(x), x.pos.lag, x-x.pos.lag)
           ..1 ..2 ..3 ..4 ..5
2009-11-01 100  NA  NA  NA  NA
2009-11-02 101 100   1 100   1
2009-11-03  97 101  -4 101  -4
2009-11-04  95  97  -2  97  -2
2009-11-05  99  95   4  95   4
2009-11-06  NA  99  NA  NA  NA
2009-11-07 104  NA  NA  99   5
2009-11-08 103 104  -1 104  -1
2009-11-09 103 103   0 103   0
2009-11-10 100 103  -3 103  -3
+3
source share
1 answer

There are no functions in R for this, but you can create an index of the initial NA positions, and then change the values ​​there after the lag.

x <- xts(c(100, 101, 97, 95, 99, NA, 104, 103, 103, 100), as.Date("2009-11-01") + 0:9)
lag.xts.na <- function(x, ...) {
    na.idx <- which(is.na(x))
    x2 <- lag.xts(x, ...)
    x2[na.idx+1,] <- x2[na.idx,]
    x2[na.idx,] <- NA
    return(x2)
}

lag.xts.na(x)
           [,1]
2009-11-01   NA
2009-11-02  100
2009-11-03  101
2009-11-04   97
2009-11-05   95
2009-11-06   NA
2009-11-07   99
2009-11-08  104
2009-11-09  103
2009-11-10  103

, - ? , ; . , timeSeries Rmetrics .

+1

Source: https://habr.com/ru/post/1721599/


All Articles