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?

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, thank you so much David! I didn't know I could pass specific variables to summarise_each_ :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.