[R] Replace zeroes in vector with nearest non-zero value

Murali.MENON at fortisinvestments.com Murali.MENON at fortisinvestments.com
Thu Jun 18 18:47:36 CEST 2009


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




More information about the R-help mailing list