[R] Re place with previous value

bartjoosen bartjoosen at hotmail.com
Thu Mar 27 11:29:46 CET 2008


Maybe something like:

f <- function(x,y) ifelse(sign(y[x])==-1,return(y[x-1]), return(y[x]))
test[,3] <- sapply(seq_along(test[,3]),f,test[,3])





Ravi S. Shankar wrote:
> 
> Hi R,
> 
> I have a dataframe with
> dim(test)
> [1] 435150      4
> class(test)
> [1] "data.frame"
> In the third column every time a number with "-" appears I need to
> replace with previous value
> I am using the following code
> s=which(substr(as.character(test[,3]),1,1)=="-")
>  for(i in 1:length(s)) test[s[i],3] = test[s[i]-1,3]
> 
> Is there a faster way of doing this?
> 
> sessionInfo()
> R version 2.5.1 (2007-06-27) 
> i386-pc-mingw32 
> 
> locale:
> LC_COLLATE=English_United States.1252;LC_CTYPE=English_United
> States.1252;LC_MONETARY=English_United
> States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252
> 
> attached base packages:
> [1] "stats"     "graphics"  "grDevices" "utils"     "datasets"
> "methods"  
> [7] "base"     
> Thanks in advance
> 
> 
> Ravi Shankar S 
>  
> 
> This e-mail may contain confidential and/or privileged i...{{dropped:10}}
> 
> ______________________________________________
> 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/Replace-with-previous-value-tp16310560p16323983.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list