I regularly need to change the values of a variable based on the values on a different variable, like this:
mtcars$mpg[mtcars$cyl == 4] <- NA
I tried doing this with dplyr
but failed miserably:
mtcars %>%
mutate(mpg = mpg == NA[cyl == 4]) %>%
as.data.frame()
How could I do this with dplyr
?
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()