2

This is with the new dplyr, to be released Real Soon Now.

The dplyr programming vignette gives an example of calling group_by with the grouping variables specified in an outer function:

my_summarise <- function(df, group_var) {
  df %>%
    group_by(!!group_var) %>%
    summarise(a = mean(a))
}

This works when supplied with a single grouping variable. However, it fails with multiple variables.

Simplified example:

f <- function(x)
{
    group_by(mtcars, !!x)
}

## works
g1 <- "cyl"
f(g1)

## doesn't work
#Error in mutate_impl(.data, dots) : 
#  Column `c("cyl", "gear")` must be length 32 (the number of rows) or one, not 2
g2 <- c("cyl", "gear")
f(g2)

How can I fix this, within the rlang framework?

Ideally I want f's signature to remain the same, ie I specify the grouping variables as a single vector rather than via a ... argument.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187

1 Answers1

3

There was a pretty similar question: Programming with dplyr using string as input. I just modified the answer a bit to use syms and !!!.

library(rlang)
f <- function(x){
  group_by(mtcars, !!!syms(x))
}

f(c("cyl")) %>% summarise(n())
# A tibble: 3 x 2
    cyl `n()`
  <dbl> <int>
1     4    11
2     6     7
3     8    14

f(c("cyl", "gear")) %>% summarise(n())
# A tibble: 8 x 3
# Groups:   cyl [?]
    cyl  gear `n()`
  <dbl> <dbl> <int>
1     4     3     1
2     4     4     8
3     4     5     2
4     6     3     2
5     6     4     4
6     6     5     1
7     8     3    12
8     8     5     2
JasonWang
  • 2,414
  • 11
  • 12