Search code examples
rxts

How to find the position of the first non-NA element in a column starting with the last element in an xts object


> vols
               vol_tr     vol_yz     vol_cl    vol_iv
2021-01-22 0.06260922 0.09798388 0.09861034        NA
2021-01-25 0.09783596 0.10595096 0.10121109 0.1362547
2021-01-26 0.10485836 0.10672985 0.10117991 0.1388527
2021-01-27 0.08284200 0.10742612 0.09586469 0.1509771
2021-01-28 0.08452010 0.11046722 0.10247347 0.1229756
2021-01-29 0.07045891 0.11292108 0.10991404        NA

I'd like to find the index of the first non-NA in column vols$vol_iv starting at the end of the column. I'm looking for index or position 5. To find the first non-NA from beginning I can do:

> d <- coredata(vols$vol_iv)
> pos = Position(function(d)!is.na(d), d)
> pos
[1] 2

Position is nice b/c it only evaluates until a match is found.


Solution

  • Trim the NA's off the right end using na.trim and then take the length of that to find the position (or use end in place of length if you want the time of the last non-NA value).

    library(xts)
    
    x <- xts(c(NA, 1, 2, 3, 4, NA), as.Date("2000-01-01")+0:5) # test input
    
    length(na.trim(x, sides = "right"))
    ## [1] 5
    

    To get the positions of both the start and end at the same time or just use rng if you want the times instead.

    rng <- range(time(na.trim(x)))
    match(rng, time(x))
    ## [1] 2 5