使用 dplyr 的 _if() 函数,例如带有否定谓词函数的 mutate_if()

MS *_*nds 4 r dplyr data-transform

根据的文档dplyr

# The _if() variants apply a predicate function (a function that
# returns TRUE or FALSE) to determine the relevant subset of
# columns.
# mutate_if() is particularly useful for transforming variables from
# one type to another
iris %>% mutate_if(is.factor, as.character)
Run Code Online (Sandbox Code Playgroud)

那么如何使用逆形式呢?我想将所有非数字值转换为字符,所以我想到这样做:

iris %>% mutate_if(!is.numeric, as.character)
#> Error in !is.numeric : invalid argument type
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。或者只选择所有非数字变量:

iris %>% select_if(!is.numeric)
#> Error in !is.numeric : invalid argument type
Run Code Online (Sandbox Code Playgroud)

也不行。

如何对,和 等函数使用否定dplyrmutate_if()select_if()arrange_if()


编辑:这可能会在即将推出的 dplyr 1.0.0: 中得到解决NEWS.md

akr*_*run 5

~我们可以使用匿名函数的简写符号tidyverse

library(dplyr)
iris %>% 
     mutate_if(~ !is.numeric(.), as.character)
Run Code Online (Sandbox Code Playgroud)

或者没有匿名函数,使用negatefrompurrr

library(purrr)
iris %>%
     mutate_if(negate(is.numeric), as.character)
Run Code Online (Sandbox Code Playgroud)

除此之外negateNegatefrombase R也可以作品

iris %>%
   mutate_if(Negate(is.numeric), as.character)
Run Code Online (Sandbox Code Playgroud)

相同的符号,适用于select_if/arrange_if

iris %>%
     select_if(negate(is.numeric))%>%
     head(2)
#  Species
#1  setosa
#2  setosa
Run Code Online (Sandbox Code Playgroud)