Reputation: 312
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:
Upvotes: 1
Views: 75
Reputation: 16856
One option doing it in two steps:
library(dplyr)
m.subset %>%
mutate(newcol = ifelse(gear + carb <= 4, TRUE, FALSE),
newcol = gear + carb + lag(newcol))
Output
gear carb temp
Mazda RX4 Wag 4 4 NA
Datsun 710 4 1 5
Hornet 4 Drive 3 1 4
Hornet Sportabout 3 2 6
Valiant 3 1 4
Duster 360 3 4 8
Upvotes: 2