Whats going on here? df<-data.frame(x=1:10,y=1:10)
ggplot()+geom_point(data=df,aes(x=x,y=y)) ## this is the normal usage right? ggplot()+geom_point(data=df,aes(x=df[,1],y=df[,2])) ## but I can also feed it column indices ggplot()+geom_point(aes(x=df[,'x'],y=df[,'y'])) ## or column names. ## but if i wrap it in a function... plot.func.one<-function(dff,x.var,y.var){ print(ggplot() + geom_point(aes(x=dff[,x.var],y=dff[,y.var]))) } plot.func.two<-function(dff,x.var,y.var){ print(ggplot() + geom_point(data=dff,aes(x=dff[,x.var],y=dff[,y.var]))) } plot.func.three<-function(dff,x.var,y.var){ print(ggplot() + geom_point(data=dff,aes(x=eval(x.var),y=eval(y.var)))) } plot.func.one(df,1,2) ## i assume the dff not found error is happening in the aes call rather than the data= portion.. plot.func.one(df,'x','y') ## but why does it work in the global env and not within a function? plot.func.two(df,1,2) plot.func.two(df,'x','y') var.x<-'x' var.y<-'y' plot.func.three(df,var.x,var.y) ## why does it give the error on y.var instead of x.var? plot.func.three(df,'x','y') dff<-df x.var<-var.x y.var<-var.y plot.func.one(dff,x.var,y.var) ## now whats going on? I assume this works because ggplot is looking globally rather than within the function... plot.func.two(dff,x.var,y.var) plot.func.three(dff,x.var,y.var) nothing seems to work right! How do I plot within a function where I can feed the function a data.frame and the columns I want plotted? I assume this is some interesting name space issue but if you guys can enlighten me as to what's going on... Thanks, Justin P.S. So before I sent this I dug some more and found my answer, aes_string: plot.func<-function(dff,x.var,y.var){ print(ggplot() + geom_point(data=dff,aes_string(x=x.var,y=y.var))) } plot.func(df,'x','y') works great. But I still wouldn't mind some clarification on what's happening in my earlier examples. [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.