2

I have a simple data_frame and want to programmatically group by a vector of column names.

Example data frame:

> a <- data_frame(g1 = c('A', 'B'), g2 = c('C', 'D'))
> a
Source: local data frame [2 x 2]

  g1 g2
1  A  C
2  B  D

Suppose I want to group by columns g1 and g2. If I wanted to hard-code the grouping, I'd do the following:

> a  %>% group_by(g1, g2)
Source: local data frame [2 x 2]
Groups: g1, g2

  g1 g2
1  A  C
2  B  D

If I wanted to programmatically pass the column names, I'd do the following:

> g1_name <- 'g1'
> g2_name <- 'g2'
> a %>% group_by_(g1_name, g2_name)
Source: local data frame [2 x 2]
Groups: g1, g2

  g1 g2
1  A  C
2  B  D

But I want to programmatically pass a vector of column names. I've tried the following, which is clearly incorrect because it only recognizes the first element in the vector (i.e., it only groups by g1):

> g_name <- c('g1', 'g2')
> a %>% group_by_(g_name)
Source: local data frame [2 x 2]
Groups: g1

  g1 g2
1  A  C
2  B  D

Any suggestions?

It seems like the solution is probably not specific to group_by, and would rather demonstrate how to convert a vector into a list of inputs for an arbitrary function. But I'll keep it in the group_by context that I need it in, in case I'm wrong.

Thanks for the help.

Eric
  • 829
  • 1
  • 8
  • 15

0 Answers0