Object not found error with ddply inside a function
Today's solution to this question is to make summarize
into here(summarize)
. e.g.
myFunction <- function(x, y){ NewColName = "a" z = ddply(x, y, here(summarize), Ave = mean(eval(parse(text=NewColName)), na.rm=TRUE) ) return(z)}
here(f)
, added to plyr in Dec 2012, captures the current context.
You can do this with a combination of do.call
and call
to construct the call in an environment where NewColName
is still visible:
myFunction <- function(x,y){NewColName <- "a"z <- do.call("ddply",list(x, y, summarize, Ave = call("mean",as.symbol(NewColName),na.rm=TRUE)))return(z)}myFunction(d.f,sv) b Ave1 0 1.52 1 3.5
I occasionally run into problems like this when combining ddply
with summarize
or transform
or something and, not being smart enough to divine the ins and outs of navigating various environments I tend to side-step the issue by simply not using summarize
and instead using my own anonymous function:
myFunction <- function(x, y){ NewColName <- "a" z <- ddply(x, y, .fun = function(xx,col){ c(Ave = mean(xx[,col],na.rm=TRUE))}, NewColName) return(z)}myFunction(df,sv)
Obviously, there is a cost to doing this stuff 'manually', but it often avoids the headache of dealing with the evaluation issues that come from combining ddply
and summarize
. That's not to say, of course, that Hadley won't show up with a solution...