non-standard-evaluation

Scoping of variables in aes(…) inside a function in ggplot

 ̄綄美尐妖づ 提交于 2019-11-26 23:16:43
问题 Consider this use of ggplot(...) inside a function. x <- seq(1,10,by=0.1) df <- data.frame(x,y1=x, y2=cos(2*x)/(1+x)) library(ggplot2) gg.fun <- function(){ i=2 plot(ggplot(df,aes(x=x,y=df[,i]))+geom_line()) } if(exists("i")) remove(i) gg.fun() # Error in `[.data.frame`(df, , i) : object 'i' not found i=3 gg.fun() # plots df[,3] vs. x It looks like ggplot does not recognize the variable i defined inside the function, but does recognize i if it is defined in the global environment. Why is that