'How to use created functions argument inside the code?

When I create a function and use arguments as variable names in group_by() function there is error:

comb <- function(z,x,y) {
  
  
df <- z  %>% group_by(flow, code, noquote(x), noquote(y) ) %>%
                summarise(TradeValue=sum(TradeValue))

}

df <- comb(data, model, cat)



Error in UseMethod("group_by") : 
  no applicable method for 'group_by' applied to an object of class "character


Solution 1:[1]

You could use the {{ }} convention in R

library(dplyr)
comb <- function(z,x,y) {
  df <- z  %>% group_by(cyl, {{x}}, {{y}} ) %>%
    summarise(hp=mean(hp))
  df
}

comb(mtcars, vs, am)
#> `summarise()` has grouped output by 'cyl', 'vs'. You can override using the
#> `.groups` argument.
#> # A tibble: 7 × 4
#> # Groups:   cyl, vs [5]
#>     cyl    vs    am    hp
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     4     0     1  91  
#> 2     4     1     0  84.7
#> 3     4     1     1  80.6
#> 4     6     0     1 132. 
#> 5     6     1     0 115. 
#> 6     8     0     0 194. 
#> 7     8     0     1 300.

Created on 2022-05-06 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DaveArmstrong