use na.locf in zoo:

> x
 [1]  0 -1 -1 -1  0  0  1 -1  1  0
> # replace 0 with NA so na.locf works
> is.na(x) <- x == 0
> x
 [1] NA -1 -1 -1 NA NA  1 -1  1 NA
> na.locf(x, na.rm=FALSE)
 [1] NA -1 -1 -1 -1 -1  1 -1  1  1
>

You can then go back and replace NAs with 0


On Thu, Jun 18, 2009 at 12:47 PM, <Murali.MENON@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<http://www.r-project.org/posting-guide.html>
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?

	[[alternative HTML version deleted]]


