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

2009-06-19 Thread Murali.MENON
Jim, Gabor, William, Thanks very much. Works a treat. Cheers, Murali -Original Message- From: William Dunlap [mailto:wdun...@tibco.com] Sent: 18 June 2009 18:27 To: MENON Murali; r-help@r-project.org Subject: RE: [R] Replace zeroes in vector with nearest non-zero value approx() almost

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

2009-06-18 Thread William Dunlap
ap TIBCO Software Inc - Spotfire Division wdunlap tibco.com > -Original Message- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of > murali.me...@fortisinvestments.com > Sent: Thursday, June 18, 2009 9:48 AM > To: r-help@r-pr

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

2009-06-18 Thread Gabor Grothendieck
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

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

2009-06-18 Thread jim holtman
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

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

2009-06-18 Thread Murali.MENON
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) {