ACMgo
ACMgo

Reputation: 31

Function writing passing column reference to group_by

I'm very new to R. Trying to define a function that groups a data set (group_by) and then creates summary statistics based on the groupings (dplyr, summarise_each).

Without defining a function the following works:

sum_stat <- data %>%
  group_by(column) %>%
  summarise_each(funs(mean), var1:var20)

The following function form does not work:

sum_stat <- function(data, column){
  data %>%
    group_by(column) %>%
    summarise_each(funs(mean), var1:var20)
}

sum_stat(data, column)

The error message returned is:

Error: unknown column 'column'

Upvotes: 2

Views: 1790

Answers (1)

joran
joran

Reputation: 173527

This is the usual way you'd do this:

foo <- function(data,column){
  data %>%
    group_by_(.dots = column) %>%
    summarise_each(funs(mean))
}

foo(mtcars,"cyl")
foo(mtcars,"gear")

Upvotes: 3

Related Questions