我不明白为什么我的极简封装函数会产生主题错误。下面应该重现它。我的目标是根据单个数据框中的数据绘制一堆图,每个图都位于一个新窗口中。
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)
为什么 R 无法在我的函数中找到“权重”?
我在 Windows 8.1 64 位上运行 R 版本 3.0.1,64 位。
谢谢!
-罗伊
最佳答案
我建议从长远来看,这样的事情是个好主意:
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
做了很多花哨的评估,在您将对象传入和传出函数的上下文中,这些评估很脆弱(容易破坏,难以理解)。 aes_string
指定 ggplot
应该根据字符串的值进行查找,而不是通常的评估语言对象的方法(即使用 "weight"
而不是 weight
)。
关于r - eval(expr, envir, enclos) 错误 : object * not found when wrapping qplot(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19897336/