Change value of variable with dplyr

luciano picture luciano · Jan 18, 2015 · Viewed 166k times · Source

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?

Answer

akrun picture akrun · Jan 18, 2015

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()