Passing a function from a parameter to a nested function

I would like to briefly run the following minimal piece of code:

library(plyr)

surround = function(my.df, my.var, my.val, my.method) {
    ddply(my.df, my.var, summarize, value = my.method(as.name(my.val)))
}

my.df = data.frame(group = rep(letters[1:4], times = 25),
                   x = rnorm(100))

surround(my.df, "group", "x", mean)

      

However, this leads to Error: could not find function "my.method"

. I understand this is a problem and I have to use eval

or substitute

, but I cannot figure it out.

+3


source to share


1 answer


If you use a custom function instead of summing it will work.



surround <- function(my.df, my.var, my.val, my.method) {
  ddply(my.df, my.var, function(x) c(value = my.method(x[[my.val]])))
}

my.df <- data.frame(group=rep(letters[1:4], times=25),
                   x=rnorm(100))

surround(my.df, "group", "x", mean)

      

+4


source







All Articles