一起使用 `mutate_at` 和 `na_if` 仅对某些列用 NA 替换零 [英] Using `mutate_at` and `na_if` together to replace zeros with NA for only some columns
问题描述
我的数据采用以下格式:
My data takes this format:
library(tidyverse)
df <- mtcars
df <- df %>% mutate(vs_doubled = vs * 2) %>% select(mpg, cyl, vs, am, vs_doubled)
head(df)
#> mpg cyl vs am vs_doubled
#> 1 21.0 6 0 1 0
#> 2 21.0 6 0 1 0
#> 3 22.8 4 1 1 2
#> 4 21.4 6 1 0 2
#> 5 18.7 8 0 0 0
#> 6 18.1 6 1 0 2
我正在尝试使用 mutate_at
和 na_if
将 0 值设置为 NA——但仅限于特定列(vs"和am").我想将vs_doubled"列保留为零.
I'm trying to use mutate_at
and na_if
to set 0 values as NA--but only for specific columns ("vs" and "am"). I would like to leave the column "vs_doubled" with zeros in it.
我不太正确,因为以下行不起作用:
I haven't quite got it right, because the following line doesn't work:
df <- df %>% mutate_at(.vars = c("vs", "am"), .funs = na_if(y = 0))
推荐答案
更新
从 dplyr
1.0.0 我们可以使用 across
:
From dplyr
1.0.0 we can use across
:
library(dplyr)
df %>% mutate(across(c(vs,am), na_if, 0)) %>% head
# mpg cyl vs am vs_doubled
#1 21.0 6 NA 1 0
#2 21.0 6 NA 1 0
#3 22.8 4 1 1 2
#4 21.4 6 1 NA 2
#5 18.7 8 NA NA 0
#6 18.1 6 1 NA 2
<小时>
原答案
在之前版本的 dplyr
中,我们可以使用 mutate_at
:
In the previous versions of dplyr
we can use mutate_at
:
df %>% mutate_at(vars(vs,am), ~na_if(.,0)) %>% head
或者另一种方式是
df %>% mutate_at(vars(vs,am), na_if, 0)
~
是 purrr 风格的公式语法,而 .
表示列的值.它是匿名函数调用的替代方法,您可以使用匿名函数调用将上述函数编写为
~
is purrr-styled formula syntax whereas .
represents value of the column. It's an alternative to anonymous function calls with which you would have written the above function as
df %>% mutate_at(vars(vs,am), function(x) na_if(x, 0))
另外所示的替代方式不需要 ~
,我们可以直接传递带有附加参数的函数(对于 y
此处为 0).
Also the alternative way shown does not require ~
and we can directly pass the function with additional arguments (which is 0 here for y
).
当然还有其他方法可以不使用 na_if
And of course there are other ways to do this without using na_if
df %>% mutate_at(vars(vs, am), ~replace(., . == 0, NA))
或与基础 R 相同
cols <- c("vs", "am")
df[cols] <- lapply(df[cols], function(x) replace(x, x == 0, NA))
这篇关于一起使用 `mutate_at` 和 `na_if` 仅对某些列用 NA 替换零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!