I have a one-column dataframe, and want to determine if the values are increasing (1) or decreasing (-1), and when no change is found return the last calculation done. I think the code I have should do it, but dplyr returns an error saying "object" "not found", and I presume it is because it is itself. Any thought on how can this be done?
df <- data.frame(Val = c(1:5,5,5,5:1,1,1,1,6,1,1,5:1))
df %>%
mutate(ValDirection = ifelse(Val > lag(Val, 1), 1,
ifelse(Val < lag(Val, 1), -1, lag(ValDirection, 1))))
Desire results should be:
df <- data.frame(Val = c(1:5,5,5,5:1, 1,1,1,6,1,1,5:1),
ValDirection = c(1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,-1))