Reputation: 3881
I a nutshell I would like to 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 do realize that this is a scoping issue and I should be using eval
or substitute
but I can't figure it out.
Upvotes: 3
Views: 50
Reputation: 11762
If you use a customised function instead of summarise, it would 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)
Upvotes: 4