1

I am not sure if what i am trying to do makes sense in R.

I want to do the something like follow:

fun <- function(df, args){
    .....
    df %>%
    group_by(args)
    .....

I am trying to pass a char vector as args, then group by the args as column name, but it does not work.

i have tried get and mget, they do not work the way i want.

Boyang Li
  • 157
  • 2
  • 11
  • see https://stackoverflow.com/questions/27688193/dplyrgroup-by-with-character-string-input-of-several-variable-names i.e. use `group_by_` – chinsoon12 Apr 25 '18 at 02:27

1 Answers1

3

Here's a small example of how to accomplish that. You pass in a string of args, we use syms from rlang to turn that into a list of symbols. We then use the !!! unquote-splice operator to group by those symbols.

library(rlang)
library(dplyr)

fun <- function(df, args){

  by <- syms(args)

   df %>%
     group_by(!!!by) %>% 
     summarize_all(mean)
  }

Using this example with mtcars:

> fun(mtcars, c("cyl"))
# A tibble: 3 x 11
    cyl   mpg  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  4.00  26.7   105  82.6  4.07  2.29  19.1 0.909 0.727  4.09  1.55
2  6.00  19.7   183 122    3.59  3.12  18.0 0.571 0.429  3.86  3.43
3  8.00  15.1   353 209    3.23  4.00  16.8 0     0.143  3.29  3.50
Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36
  • 1
    You do not need `rlang` anymore just `!!by` https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html – BENY Apr 25 '18 at 02:45
  • `syms` isn't exported by `dplyr`. OP requested input as a character vector, so `rlang` is required. – Jake Kaupp Apr 25 '18 at 11:15