用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
?
推荐答案
我们可以使用替换
将mpg中的值更改为对应于$ $ c的 NA
$ c> 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屋!
查看全文