The zoo package has na.locf which replaces NAs with the last non-NA.
So, first replace 0's with NA's, apply na.locf and then replace NAs with 0's.

> library(zoo)
> x.na <- replace(x, x == 0, NA)
> x0 <- na.locf(x.na, na.rm = FALSE)
> replace(x0, is.na(x0), 0)
 [1]  0 -1 -1 -1 -1 -1  1  1  1  1

On Thu, Jun 18, 2009 at 12:47 PM, <murali.me...@fortisinvestments.com> wrote:
> Folks,
>
> If I have a vector such as the following:
>
> x <- c(0, -1, -1, -1, 0, 0, 1, -1, 1, 0)
>
> and I want to replace the zeroes by the nearest non-zero number to the
> left, is there a more elegant way to do this than the following loop?
>
> y <- x
> for (i in 2 : length(x))
> {
>    if (y[i] == 0) {
>        y[i] <- y[i - 1]
>    }
> }
>
>> y
> [1]  0 -1 -1 -1 -1 -1  1 -1  1  1
>
> You can see the first zero is left as is, the next two zeroes become -1,
> which is the closest non-zero to the left of them, and the last zero
> becomes 1.
>
> Cheers,
> Murali
>
> ______________________________________________
> R-help@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.
>

______________________________________________
R-help@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.

Reply via email to