Changing a variable value with dplyr

I regularly need to change the values ​​of a variable based on the values ​​for another variable, for example:

mtcars$mpg[mtcars$cyl == 4] <- NA 

I tried to do this with dplyr , but failed:

 mtcars %>% mutate(mpg = mpg == NA[cyl == 4]) %>% as.data.frame() 

How can I do this with dplyr ?

+42
r dataframe dplyr plyr
Jan 18 '15 at 7:28
source share
1 answer

We can use replace to change the values ​​in "mpg" to NA , which corresponds to cyl==4 .

 mtcars %>% mutate(mpg=replace(mpg, cyl==4, NA)) %>% as.data.frame() 
+108
Jan 18 '15 at 19:33
source share



All Articles