3

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

0

1 Answer 1

5

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
## ..   ...  ... ..
1
  • 1
    summarise(n=n()) is the same as tally, I think. There's also the count function, but I'm not sure if it'll play nice with this approach.
    – Frank
    Commented Jun 29, 2015 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.