简体   繁体   English

如何在函数中使用 tidyverse 引用变量(列名)?

[英]How to refer to variable (column name) with tidyverse in a function?

This question is linked to this one but I cannot get it to work when I want to use multiple functions.这个问题与这个问题有关,但是当我想使用多个功能时,我无法让它工作。 I have a function as follows:我有一个功能如下:

f3 <- function(x){
    d <- mtcars %>% group_by(cyl, gear) %>% summarize(across(all_of(x), 
                                                      m = mean(x), 
                                                      sd = sd(x),
                                                      n = length(x),
                                                      se = sd / sqrt(n),
                                                      tscore = qt(0.975, n-1),
                                                      margin = tscore * se,
                                                      uppma = mean + margin,
                                                      lowma = mean - margin),
                                                      .groups = 'drop')
 }

But when I call the function like this it doesn't work:但是当我这样调用函数时它不起作用:

d <- f3(x = c('wt'))

My required output is df with columns called m, sd, n, se, tscore, margin, uppma, lowma with the result of that function across the groups I made with group_by()我需要的输出是 df,列名为m, sd, n, se, tscore, margin, uppma, lowma ,该函数的结果是我使用group_by()创建的组

You can call the function using symbols rather than strings for the column names by using the {{ ('curly curly') operator:您可以使用{{ ('curly curly') 运算符使用符号而不是字符串作为列名调用函数:

library(tidyverse)

f3 <- function(x){
 mtcars %>% 
    group_by(cyl, gear) %>% 
    summarize(m = mean({{x}}), 
         sd = sd({{x}}),
         n = length({{x}}),
         se = sd / sqrt(n),
         tscore = qt(0.975, n-1),
         margin = tscore * se,
         uppma = m + margin,
         lowma = m - margin,
         .groups = 'drop')
}

f3(x = wt)
#> # A tibble: 8 x 10
#>     cyl  gear     m     sd     n     se tscore  margin  uppma   lowma
#>   <dbl> <dbl> <dbl>  <dbl> <int>  <dbl>  <dbl>   <dbl>  <dbl>   <dbl>
#> 1     4     3  2.46 NA         1 NA     NaN    NaN     NaN    NaN    
#> 2     4     4  2.38  0.601     8  0.212   2.36   0.502   2.88   1.88 
#> 3     4     5  1.83  0.443     2  0.314  12.7    3.98    5.81  -2.16 
#> 4     6     3  3.34  0.173     2  0.123  12.7    1.56    4.89   1.78 
#> 5     6     4  3.09  0.413     4  0.207   3.18   0.657   3.75   2.44 
#> 6     6     5  2.77 NA         1 NA     NaN    NaN     NaN    NaN    
#> 7     8     3  4.10  0.768    12  0.222   2.20   0.488   4.59   3.62 
#> 8     8     5  3.37  0.283     2  0.2    12.7    2.54    5.91   0.829

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

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