I'd like to replace the following for-loop ...
data <- data.frame(x = c(2, 3, 3, 4, 5, 6, 5, 5, 6, 8, 9, 7, 6, 9, 10),
y = rep(0, 15))
for (i in 2:length(data$x)) {
data$y[i] <- ifelse(data$x[i] > data$y[i-1], data$y[i-1] + 2, data$y[i-1] - 1)
}
data$y # 0 2 4 3 5 7 6 5 7 9 8 7 6 8 10
... and I want to use dplyr and tried the following:
data %>%
mutate(y = if_else(x > lag(y), lag(y) + 2, lag(y) -1 ))
But obviously I didn't succeed. Any help would be much appreciated.
ifelseorif_elseorcase_whendon't help here. The for loop is going step-by-step through the data and calculates each y on the basis of the previous y. My guess was to usemap.Reducewith the argumentaccumulateset toTRUE