在dplyr中总结的函数中使用quasiquotation

发布于 2025-01-27 22:35:13 字数 612 浏览 4 评论 0原文

我正在尝试编写一个函数,该功能可以将列名作为字符串分配给变量并为其产生汇总输出的字符串,因此

my_function <- function(my_df, columnA,columnB){
    

    summ_df <- my_df %>% 
        group_by(cyl) %>% 
        summarise(base_mean = mean(columnA),
                  contrast_mean = mean(columnB)) 
    
    return(summ_df)
    }


    base = "drat"
    cont = "wt"
    my_function(mtcars,base,cont)

我想要的是,上述功能会返回相同的内容,因为

mtcars %>% 
    group_by(cyl) %>% 
    summarise(base_mean = mean(drat),
              contrast_mean = mean(wt)) 

我确定它是否是某种组合enexpr,或ensym和!但是我不断获得NA值

I'm trying to write a function that can take column names as strings assigned to variables and produce a summarized output for them like so

my_function <- function(my_df, columnA,columnB){
    

    summ_df <- my_df %>% 
        group_by(cyl) %>% 
        summarise(base_mean = mean(columnA),
                  contrast_mean = mean(columnB)) 
    
    return(summ_df)
    }


    base = "drat"
    cont = "wt"
    my_function(mtcars,base,cont)

What I would want is that the above function would return the same thing as

mtcars %>% 
    group_by(cyl) %>% 
    summarise(base_mean = mean(drat),
              contrast_mean = mean(wt)) 

I'm sure it's some combination of enexpr, or ensym, and !! but i keep getting NA values

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囍孤女 2025-02-03 22:35:13

!! 使用

my_function <- function(my_df, columnA,columnB){
    

    my_df %>% 
        group_by(cyl) %>% 
        summarise(base_mean = mean(!! ensym(columnA)),
                  contrast_mean = mean(!! ensym(columnB)), .groups = 'drop' )
    
   
    }

使用ENSYM

> my_function(mtcars, !!base, !!cont)
# A tibble: 3 × 3
    cyl base_mean contrast_mean
  <dbl>     <dbl>         <dbl>
1     4      4.07          2.29
2     6      3.59          3.12
3     8      3.23          4.00

Use ensym with !! so that it can take both unquoted and quoted actual arguments

my_function <- function(my_df, columnA,columnB){
    

    my_df %>% 
        group_by(cyl) %>% 
        summarise(base_mean = mean(!! ensym(columnA)),
                  contrast_mean = mean(!! ensym(columnB)), .groups = 'drop' )
    
   
    }

-testing

> my_function(mtcars, !!base, !!cont)
# A tibble: 3 × 3
    cyl base_mean contrast_mean
  <dbl>     <dbl>         <dbl>
1     4      4.07          2.29
2     6      3.59          3.12
3     8      3.23          4.00
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文