使用 dplyr 更改变量的值 [英] Change value of variable with dplyr
本文介绍了使用 dplyr 更改变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常需要根据不同变量的值更改变量的值,如下所示:
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
我尝试用 dplyr
做这件事,但失败得很惨:
I tried doing this with dplyr
but failed miserably:
mtcars %>%
mutate(mpg = mpg == NA[cyl == 4]) %>%
as.data.frame()
我怎样才能用 dplyr
做到这一点?
How could I do this with dplyr
?
推荐答案
我们可以使用replace
将'mpg'中的值改为NA
对应 cyl==4
.
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()
这篇关于使用 dplyr 更改变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文