mutate_if的正确语法 [英] Correct syntax for mutate_if
问题描述
我想通过dplyr
中的mutate_if
将NA
值替换为零.语法如下:
I would like to replace NA
values with zeros via mutate_if
in dplyr
. The syntax below:
set.seed(1)
mtcars[sample(1:dim(mtcars)[1], 5),
sample(1:dim(mtcars)[2], 5)] <- NA
require(dplyr)
mtcars %>%
mutate_if(is.na,0)
mtcars %>%
mutate_if(is.na, funs(. = 0))
返回错误:
vapply(tbl, p, logical(1), ...)
中的错误:值必须为长度1, 但是FUN(X[[1]])
结果是长度32
Error in
vapply(tbl, p, logical(1), ...)
: values must be length 1, butFUN(X[[1]])
result is length 32
此操作的正确语法是什么?
What's the correct syntax for this operation?
推荐答案
I learned this trick from the purrr tutorial, and it also works in dplyr.
There are two ways to solve this problem:
First, define custom functions outside the pipe, and use it in mutate_if()
:
any_column_NA <- function(x){
any(is.na(x))
}
replace_NA_0 <- function(x){
if_else(is.na(x),0,x)
}
mtcars %>% mutate_if(any_column_NA,replace_NA_0)
第二,使用~
,.
或.x
的组合.(.x
可以替换为.
,但不能替换任何其他字符或符号):
Second, use the combination of ~
,.
or .x
.( .x
can be replaced with .
, but not any other character or symbol):
mtcars %>% mutate_if(~ any(is.na(.x)),~ if_else(is.na(.x),0,.x))
#This also works
mtcars %>% mutate_if(~ any(is.na(.)),~ if_else(is.na(.),0,.))
根据您的情况,您还可以使用mutate_all()
:
In your case, you can also use mutate_all()
:
mtcars %>% mutate_all(~ if_else(is.na(.x),0,.x))
使用~
,我们可以定义一个匿名函数,而.x
或.
代表变量.在mutate_if()
情况下,每一列都是.
或.x
.
Using ~
, we can define an anonymous function, while .x
or .
stands for the variable. In mutate_if()
case, .
or .x
is each column.
这篇关于mutate_if的正确语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!