Change value of variable with dplyr

RDataframePlyrDplyr

R Problem Overview


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?

R Solutions


Solution 1 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlucianoView Question on Stackoverflow
Solution 1 - RakrunView Answer on Stackoverflow