用dplyr改变变量的值[重复]

时间:2022-11-26 23:42:08

This question already has an answer here:

这个问题已经有了答案:

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:

我试着用dplyr做这个,但失败的很惨:

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

How could I do this with dplyr?

我怎么用dplyr做这个?

1 个解决方案

#1


136  

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

我们可以用replace将“mpg”中的值改为NA,对应于cyl==4。

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

#1


136  

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

我们可以用replace将“mpg”中的值改为NA,对应于cyl==4。

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()