mutate_if的正确语法 [英] Correct syntax for mutate_if

查看:789
本文介绍了mutate_if的正确语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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, but FUN(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆