How group_by is multiple flexible criteria
I am trying to use group_by inside a function, with the grouping criteria being the input of the function. Right now I have configured it like this:
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 like so:
example <- x(data = my_data, grouping_vector = c(col1, col2))
it fails. Is there a way to pass multiple group_by objects to this function? I know that you can just simply separate multiple columns with a comma, but I don't know how to do this in a function.
thank
+3
source to share
1 answer
Make sure grouping_vector
to pass the argument .dots
:
x <- function(data, grouping_vector) {
data %>%
group_by_(.dots = grouping_vector) %>%
summarise(n = n())
}
# example
data(ChickWeight)
x(ChickWeight, c("Chick", "Diet"))
gives:
## 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
## .. ... ... ..
+5
source to share