I don't understand why my oh-so-minimal wrapper function produces the subject error. The below should reproduce it. My goal is to do a bunch of plots from data in a single dataframe, each of which lives in a new window.
library(ggplot2)
library(datasets)
data(ChickWeight)
str(ChickWeight)
# This works fine:
qplot(x = weight, y = Time, data = ChickWeight, color = Diet)
myfun <- function(pred = weight, resp = Time, dat = ChickWeight) {
windows()
qplot(x = pred, y = resp, data = dat, color = Diet)
}
# But this returns 'Error in eval(expr, envir, enclos) : object 'weight' not found':
myfun()
# As does this
myfun(weight, Time)
Why can't R find 'weight' in my function?
I'm running R version 3.0.1, 64-bits on windows 8.1 64-bits.
Thanks!
-Roy
I would suggest that in the long run something like this would be a good idea:
myfun <- function(pred = "weight", resp = "Time", dat = ChickWeight) {
dev.new() ## more general than windows()
ggplot(dat,aes_string(x=pred,y=resp,color="Diet"))+geom_point()
}
myfun()
qplot
does a lot of fancy evaluation which will be fragile (easy to break, hard to understand) in a context where you are passing objects in and out of functions. aes_string
specifies that ggplot
should base its lookup on the value of a string, rather than its usual approach of evaluating a language object (i.e. using "weight"
rather than weight
).