3

This question is related to the a similar post. Function writing passing column reference to group_by

However, I want to pass several inputs to a function that uses group_by_() and summarise_().

Here's my function:

foo <- function(data,column,x1,x2){
    data %>%
            group_by_(.dots = column) %>%
            summarise_(.dots= c(~mean(x1), ~mean(x2)))
}

However, when I run

foo(mtcars,"cyl", "disp", "hp")

I get the following error.

Error in UseMethod("as.lazy_dots") : 
  no applicable method for 'as.lazy_dots' applied to an object of class "c('double', 'numeric')"
In addition: Warning message:
In mean.default(x1) : argument is not numeric or logical: returning NA

Can anyone tell me where I'm doing wrong?

Community
  • 1
  • 1
asiehh
  • 553
  • 12
  • 22
  • I noticed that you didn't accept any answer on any of the questions you asked. Although it is not mandatory to accept an answer, it is considered good practice to do so if one of the answers worked for you. This will give future readers a clue about the value of the solution. See also this help page: [What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answers) – Jaap Oct 23 '15 at 09:03

1 Answers1

6

Well, it looks like you just want summarise_each again, which does have a standard evaulation alternative, summarise_each_. You can write foo as

foo <- function(data, column, x1, x2){
    data %>%
            group_by_(.dots = column) %>%
            summarise_each_(funs(mean), c(x1,x2))
}

and call it with

foo(mtcars,"cyl", "disp", "hp")
# Source: local data frame [3 x 3]
# 
#     cyl     disp        hp
#   (dbl)    (dbl)     (dbl)
# 1     4 105.1364  82.63636
# 2     6 183.3143 122.28571
# 3     8 353.1000 209.21429
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Oh, thank you so much David! I didn't know I could pass specific variables to summarise_each_ :) – asiehh Oct 22 '15 at 21:31