3

I am trying to use dplyr's group_by in a local function, example:

testFunction <- function(df, x) {
  df %>%
group_by(x) %>%
summarize(mean.Petal.Width = mean(Petal.Width))
}

testFunction(iris, Species)

and I get an error "... unknown variable to group by: x" I've tried group_by_ and it gives me a summary of the entire dataset. Anybody have a clue how I can fix this?

Thanks in advance!

Axeman
  • 32,068
  • 8
  • 81
  • 94
RoseS
  • 185
  • 2
  • 12

2 Answers2

2

Here is one way to work with the new enquo from dplyr, where enquo takes the string and converts to quosure which gets evaluated by unquoting (UQ or !!) in group_by, mutate, summarise etc.

library(dplyr)
testFunction <- function(df, x) {
 x <- enquo(x)
  df %>%
    group_by(!! x) %>%
     summarize(mean.Petal.Width = mean(Petal.Width))
 }

testFunction(iris, Species)
# A tibble: 3 x 2
#     Species mean.Petal.Width
#      <fctr>            <dbl>
#1     setosa            0.246
#2 versicolor            1.326
#3  virginica            2.026
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    cool. That works, thank you very much. Do you have a reference url that covers this? – RoseS Jun 20 '17 at 18:34
  • @RoseS You can check [here](http://dplyr.tidyverse.org/articles/programming.html#quoting) – akrun Jun 20 '17 at 18:37
0

I got it to work like this:

testFunction <- function(df, x) {
                      df %>%
                         group_by(get(x)) %>%
                         summarize(mean.Petal.Width = mean(Petal.Width))
                 }

testFunction(iris,"Species")

I changed x to get(x), and Species to "Species" in testFunction(iris,...).

CPak
  • 13,260
  • 3
  • 30
  • 48
  • I tried 20 things, so don't ask me why it works...;) – CPak Jun 20 '17 at 18:13
  • hmmm, I think the 'get(x)' helps... it seems to understand what to group by now. Now I get the error ".... object "Species" not found" , so I'm not able to get it to work with or without quotes when calling the function. Do you have an idea why that might work for you? Ha! I just saw "...don't ask me how it works" – RoseS Jun 20 '17 at 18:18
  • Do you have `dplyr` loaded? Updated `dplyr`? You could also try `akrun` answer...which should be equivalent. – CPak Jun 20 '17 at 18:21
  • I did not have the updated dplyr loaded until after seeing Akrun's response, so that might be it. Thank you so much for your help! – RoseS Jun 20 '17 at 18:59