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
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
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
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
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) {
5 matches
Mail list logo