简体   繁体   English

如何将列名作为使用 dplyr 的 function 的参数传递,而不将其作为字符串传递?

[英]How to pass a column name as an argument of a function which uses dplyr, without passing it as a string?

Here: https://rpubs.com/hadley/dplyr-programming they write the following.这里: https://rpubs.com/hadley/dplyr-programming他们写了以下内容。

my_summarise <- function(df, group_by) {
  group_by <- enquo(group_by)
  print(group_by)

  df %>%
    group_by(!!group_by) %>%
    summarise(a = mean(a))
}

my_summarise(df, g1)
#> ~g1
#> # A tibble: 2 × 2
#>      g1     a
#>   <dbl> <dbl>
#> 1     1   4.5
#> 2     2   2.0

So I try to copy it, using my idea of a function and my data.所以我尝试复制它,使用我对 function 的想法和我的数据。

library(MASS)
not.fun <- function(data, column) {
  column <- enquo(column)
  data %>% slice(1:10) %>% select(!!column)
}

not.fun(MASS::Cars93, Length)
Error in select(., !!column) : unused argument (!!column) 

But, guess what, it doesn't work.但是,你猜怎么着,它不起作用。 How to make it work, without using strings?如何在不使用字符串的情况下使其工作? I would be interested in a result possibly done in base R if it'd take as many lines of code to write as a result in some specific package.如果需要编写与某些特定 package 中的结果一样多的代码行,我会对可能在 base R 中完成的结果感兴趣。

The MASS package has it's own select() function. If you load MASS after you load dplyr , you mask the dplyr version of the function. You could be expliclt about which select function you want: MASS package 有自己的select() function。如果在加载dplyr后加载 MASS,则会屏蔽 function 的dplyr版本。你可能会明确知道你想要哪个 881274218065888

library(MASS)
not.fun <- function(data, column) {
  column <- enquo(column)
  data %>% slice(1:10) %>% dplyr::select(!!column)
}

not.fun(MASS::Cars93, Length)

It is likely to be an issue of function masking as @MrFlick described in his post.正如@MrFlick 在他的帖子中所述,这很可能是 function 屏蔽的问题。 If that issue is resolved, instead of the enquo/!!如果该问题得到解决,而不是enquo/!! the curly-curly operator can be used {{..}} as well curly-curly 运算符也可以使用{{..}}

not.fun <- function(data, column) { 
                    data %>%
                         slice(1:10) %>%
                         dplyr::select({{column}})
   }


not.fun(MASS::Cars93, Length)
#   Length
#1     177
#2     195
#3     180
#4     193
#5     186
#6     189
#7     200
#8     216
#9     198
#10    206

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM