This question already has an answer here:
这个问题已经有了答案:
- Set certain values to NA with dplyr 3 answers
- 用dplyr 3的答案将某些值设置为NA。
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()