I am trying to mutate a new column in mtcars, but make the new entry (row) dependent in on the just-previous row in the same column (the example using mtcars is admittedly nonsense).
Simplify mtcars with...
m.subset <- mtcars[2:7, 10:11] # top few rows and only the relevant columns
Similar questions have been asked...
Reuse value of previous row during dplyr::mutate
use the diff function with mutate at from dplyr
...and others, but all seem to refer to existing columns, not the subject one -- or they refer to multiple columns/rows as they currently exist.
For example, neither of the following work:
mtcars1 <- mtcars %>% # doesn't work
mutate (
newcol = gear + carb +
ifelse(shift(newcol, n=1, type = "lag") >4, 0, 1)
)
mtcars1 <- mtcars %>% # doesn't work
mutate (
newcol = gear + carb +
ifelse(shift(., n=1, type = "lag") >4, 0, 1)
)
...and while the following works, it's wrong:
mtcars1 <- mtcars %>% # works but wrong
mutate (
newcol = gear + carb +
ifelse(lag(.) >4, 0, 1)
)
Result I am looking for is: