[R] Odp: Vector replace 0 elements without using a loop

William Dunlap wdunlap at tibco.com
Thu Oct 7 18:16:58 CEST 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Petr PIKAL
> Sent: Thursday, October 07, 2010 12:13 AM
> To: rivercode
> Cc: r-help at r-project.org
> Subject: [R] Odp: Vector replace 0 elements without using a loop
> 
> Hi
> 
> 
> r-help-bounces at r-project.org napsal dne 07.10.2010 07:16:01:
> 
> > 
> > Hi,
> > 
> > With a vector like:
> > 
> > x = c (22, 23, 22.5, 0,0,24, 0, 23.2, 23.5, 0,0,0, 26)
> > 
> > How can I replace the 0's with the previous last value 
> without looping
> > through the vector ?
> 
> Change your zeroes to NA values
> x[x==0]<-NA
> 
> use na.locf function from zoo package
> 
> library(zoo)
> 
> x<-na.locf(x)
> 
> Regards
> Petr

Or if you want to do it from scratch try defining the
following function.  For each element of the logical
vector x it returns the index of the last TRUE
entry up to that point.

indexOfMostRecentTrueEntry <- function (x) 
{
    stopifnot(is.logical(x))
    x <- x & !is.na(x) # treat NA's as FALSE's
    retval <- cummax(seq_along(x) * x)
    retval[retval == 0] <- NA # in case x starts with FALSE
    retval
}

and get your result with

  x[indexOfMostRecentTrueEntry(x!=0)] 

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> 
> 
> > 
> > Something tells me I am missing the obvious.
> > 
> > Thanks,
> > Chris
> > -- 
> > View this message in context: 
> http://r.789695.n4.nabble.com/Vector-replace-0-
> > elements-without-using-a-loop-tp2966191p2966191.html
> > Sent from the R help mailing list archive at Nabble.com.
> > 
> > ______________________________________________
> > R-help at 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 at 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.
> 



More information about the R-help mailing list