[R] last observation carried forward +1

Gabor Grothendieck ggrothendieck at gmail.com
Fri Sep 30 14:01:46 CEST 2011


On Fri, Sep 30, 2011 at 5:43 AM, Jan Wijffels <jwijffels at bnosac.be> wrote:
> Hi R-helpers
>
> I'm looking for a vectorised function which does missing value replacement
> as in last observation carried forward in the zoo package but instead of a
> locf, I would like the locf function to add +1 to each time a missing value
> occurred. See below for an example.
>
>> require(zoo)
>> x <- 5:15
>> x[4:7] <- NA
>> coredata(na.locf(zoo(x)))
>  [1]  5  6  7  7  7  7  7 12 13 14 15
> But what I need is
> 5  6  7  7+1  7+1+1  7+1+1+1  7+1+1+1+1 12 13 14 15
> to obtain
> [1]  5  6  7  8  9 10 11 12 13 14 15
> I could program this in C but if anyone has already done this I would be
> interested in seeing their vectorized solution.
>

Try this (where x is from the question):

> ix <- cumsum(is.na(x))
> na.locf(x) + ix - cummax(ix * !is.na(x))
 [1]  5  6  7  8  9 10 11 12 13 14 15

Because of the way x was constructed in this test case the result is
actually the same as linear interpolation (though not in general) so
if that were what is wanted then it would just be:

> na.approx(x)
 [1]  5  6  7  8  9 10 11 12 13 14 15

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list