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. ______________________________________________ R-help@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.