简体   繁体   English

在函数中将字符串作为 arguments 传递时如何保留列名

[英]How to retain column name when passing strings as arguments in functions

I have a function which takes a column name as an input:我有一个 function 它将列名作为输入:

library(tidyverse)

dat <- diamonds

ex_func <- function(df, grp) {
  df %>% 
    distinct(cut, get(grp))
}

ex_func(dat, grp = "color")

How exactly do I get the name of the second column in the resulting group to be the input (eg "color", rather than get(grp))?我如何将结果组中第二列的名称作为输入(例如“颜色”,而不是 get(grp))?

If we are using both unquoted or quoted value, then use ensym and evaluate ( !! )如果我们同时使用未引用或引用的值,则使用ensym并评估 ( !! )

library(dplyr)
ex_func <- function(df, grp) {
     df %>% 
           distinct(cut, !! rlang::ensym(grp))
   }   

-testing -测试

ex_func(dat, "color")
# A tibble: 35 x 2
#   cut       color
#   <ord>     <ord>
# 1 Ideal     E    
# 2 Premium   E    
# 3 Good      E    
# 4 Premium   I    
# 5 Good      J    
# 6 Very Good J    
# 7 Very Good I    
# 8 Very Good H    
# 9 Fair      E    
#10 Ideal     J    
# … with 25 more rows

ex_func(dat, color)
# A tibble: 35 x 2
#   cut       color
#   <ord>     <ord>
# 1 Ideal     E    
# 2 Premium   E    
# 3 Good      E    
# 4 Premium   I    
# 5 Good      J    
# 6 Very Good J    
# 7 Very Good I    
# 8 Very Good H    
# 9 Fair      E    
#10 Ideal     J    
# … with 25 more rows

If we prefer to use only unquoted, the option is {{}}如果我们更喜欢只使用不带引号的,选项是{{}}

ex_func <- function(df, grp) {
     df %>% 
           distinct(cut, {{grp}})
   }   

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

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