aes 中的局部变量 [英] Local Variables Within aes
本文介绍了aes 中的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我用 ggplot 绘图时,我试图在 aes
中使用局部变量.这是我的问题归结为本质:
I'm trying to use a local variable in aes
when I plot with ggplot. This is my problem boiled down to the essence:
xy <- data.frame(x=1:10,y=1:10)
plotfunc <- function(Data,YMul=2){
ggplot(Data,aes(x=x,y=y*YMul))+geom_line()
}
plotfunc(xy)
这会导致以下错误:
Error in eval(expr, envir, enclos) : object 'YMul' not found
似乎我不能在 aes
中使用局部变量(或函数参数).会不会是因为aes
的内容在局部变量超出作用域的情况下被执行了?我怎样才能避免这个问题(除了不使用 aes
中的局部变量)?
It seems as if I cannot use local variables (or function arguments) in aes
. Could it be that it occurrs due to the content of aes
being executed later when the local variable is out of scope? How can I avoid this problem (other than not using the local variable within aes
)?
推荐答案
我会捕捉本地环境,
xy <- data.frame(x=1:10,y=1:10)
plotfunc <- function(Data, YMul = 2){
.e <- environment()
ggplot(Data, aes(x = x, y = y*YMul), environment = .e) + geom_line()
}
plotfunc(xy)
这篇关于aes 中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文