[R] Conditionally adding a constant
Rui Barradas
ruipbarradas at sapo.pt
Mon Jan 2 13:47:09 CET 2012
Hello,
I believe this works.
f1 <- function(x){
for(i in 2:length(x)) x[i] <- ifelse(x[i-1] > 3, x[i-1] + 2, x[i])
x
}
f2 <- function(x){
for(i in 2:length(x)) x[i] <- ifelse(is.na(x[i]) & (x[i-1] > 3), x[i-1] +
2, x[i])
x
}
df <- data.frame(x = c(1,2,3,4,5), y = c(10,20,30,NA,NA))
apply(df, 2, f1) # df$x[4] > 3, df$x[5] also changes
apply(df, 2, f2) # only df$y has NA's
Maybe there's a better way, avoiding the loop.
Rui Barradas
--
View this message in context: http://r.789695.n4.nabble.com/Conditionally-adding-a-constant-tp4253049p4253125.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list