r - mutate_if 的正确语法

标签 r dplyr na

我想通过 dplyr 中的 mutate_ifNA 值替换为零。语法如下:

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))

返回错误:

Error in vapply(tbl, p, logical(1), ...) : values must be length 1, but FUN(X[[1]]) result is length 32

此操作的正确语法是什么?

最佳答案

我从 purrr tutorial 学到了这个技巧,并且它也适用于 dplyr。 有两种方法可以解决这个问题:
首先,在管道外部定义自定义函数,并在 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可替换)的组合与 .,但不包含任何其他字符或符号):

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():

mtcars %>% mutate_all(~ if_else(is.na(.x),0,.x))

使用~,我们可以定义一个匿名函数,而.x.代表变量。在 mutate_if() 情况下,..x 是每一列。

关于r - mutate_if 的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42052078/

相关文章:

r - 如何将 NAs 放在 dplyr 中进行排序?

r - 查找和替换NA中DataFrame中所有列的值

r - 如果矩阵包含任何NA,如何返回TRUE?

python - 从 Graphlab SFrame 的特定列中查找具有 "Not Applicable"值的行

list - 从 R 中的 glm 中提取系数

r - RSelenium 的问题

r - 如何使用 Azure AD 身份验证在 Azure 应用服务中配置 Shiny

R 将列按行转换为 JSON

r - 使用 R tidyverse 将 double 转换为整数

r - dplyr 中是否有 "unfilter"用于将更改与原始数据集合并?