ila
ila

Reputation: 766

How to group_by multiple, flexible criteria

I'm trying to use group_by inside a function, with the grouping criteria being an input of the function. Right now I have it set up as so:

x <- function(data, grouping_vector) {
  data %>%
    group_by_(grouping_vector) %>%
    summarise(n = n()) -> output
  output
}

... but when I try to use this function on a list of multiple grouping items as so:

example <- x(data = my_data, grouping_vector = c(col1, col2))

it fails. Is there a way to feed multiple group_by subjects into that function? I know you can simply separate multiple columns by a comma normally, but I don't know how I would do that in a function.

Thanks

Upvotes: 3

Views: 207

Answers (1)

aaronwolen
aaronwolen

Reputation: 3753

Make sure grouping_vector is passed to the .dots argument:

x <- function(data, grouping_vector) {
  data %>%
    group_by_(.dots = grouping_vector) %>%
    summarise(n = n())
}


# example
data(ChickWeight)
x(ChickWeight, c("Chick", "Diet"))

produces:

##    Chick Diet  n
## 1     18    1  2
## 2     16    1  7
## 3     15    1  8
## 4     13    1 12
## 5      9    1 12
## 6     20    1 12
## 7     10    1 12
## 8      8    1 11
## 9     17    1 12
## 10    19    1 12
## ..   ...  ... ..

Upvotes: 5

Related Questions