Home > Blockchain >  How to refer to variable (column name) with tidyverse in a function?
How to refer to variable (column name) with tidyverse in a function?

Time:07-22

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()

CodePudding user response:

You can call the function using symbols rather than strings for the column names by using the {{ ('curly curly') operator:

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
  • Related