带有空括号的dplyr :: mutate_all调用函数

时间:2019-02-27 11:39:34

标签: r dplyr

这可能是一个已知的行为,但我觉得很奇怪-是否有原因为什么在带有空括号的mutate_all中调用一个函数不会给出任何结果(没有突变),没有错误或警告?

library(tidyverse)
sample_df <- data_frame(id = 1:3, name = letters[1:3])

# with parenthesis
sample_df %>% mutate_all(as.character()) %>% str

#> Classes 'tbl_df', 'tbl' and 'data.frame':    3 obs. of  2 variables:
#>  $ id  : int  1 2 3
#>  $ name: chr  "a" "b" "c"

# without parenthesis
sample_df %>% mutate_all(as.character) %>% str

#> Classes 'tbl_df', 'tbl' and 'data.frame':    3 obs. of  2 variables:
#>  $ id  : chr  "1" "2" "3"
#>  $ name: chr  "a" "b" "c"

reprex package(v0.2.1)于2019-02-27创建

1 个答案:

答案 0 :(得分:1)

据我了解,这是由于dplyr的非标准评估(NSE)引起的。来自?mutate_all文档(黑体字)

  

.funs:“ funs()”,或字符生成的函数调用列表            函数名称的向量,或者简称为函数。

所以dplyr的NSE意味着我们可以写

sample_df %>% mutate_all("as.character")

sample_df %>% mutate_all(as.character)

换句话说,我们可以将函数名称提供为符号或字符向量。


另一方面,请注意as.character()的返回方式

character(0)

如此

sample_df %>% mutate_all(as.character())

对应于传递一个空的函数名。