Skip to content

Replace with previous value

2 messages · Ravi S. Shankar, Bart Joosen

#
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}}
#
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: