[R] how to replace NA with previous numbers

Gabor Grothendieck ggrothendieck at gmail.com
Thu Nov 20 05:43:48 CET 2008


See na.locf in the zoo package.

On Wed, Nov 19, 2008 at 10:59 PM, jeffc <hcen at andrew.cmu.edu> wrote:
>
> Hi,
>
> I have a vector with lots of NAs. e.g.
> vec = c(NA, NA, 2, NA, NA, 5, NA, 6, NA)
>> vec
> [1] NA NA  2 NA NA  5 NA  6 NA
>
> I would like to replace NAs with their immediately previous non NA number.
> After replacement, the above vector will become
>> vec
> [1] 0 0 2 2 2 5 5 6 6.
>
> I understand  how to do that with a loop but the actual vector is very long
> and the loop takes too much time in R. Is there a good way to do the
> replacement?
>
> thanks a lot
>
> Jeff
>
> --
> View this message in context: http://www.nabble.com/how-to-replace-NA-with-previous-numbers-tp20594635p20594635.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list