Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Variables Within aes

Tags:

r

ggplot2

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) 

This results in the following error:

Error in eval(expr, envir, enclos) : object 'YMul' not found 

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)?

like image 239
fabb Avatar asked May 18 '12 20:05

fabb


People also ask

What are local variables?

A local variable is a type of variable that can be used where the scope and extent of the variable is within the method or statement block in which it is declared. It is used as an iteration variable in the foreach statement, exception variable in the specific-catch clause and resource variable in the using statement.

How do you declare local variables?

Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block. Access modifiers cannot be used for local variables.

What are local variables examples?

Declaration of Local Variable: In this case it is executed in the same manner as if it were part of a local variable declaration statement. For example: for(int i=0;i<=5;i++){……} In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.

Where are local variables used?

Local variables are useful when you only need that data within a particular expression. For example, if you need to reuse a calculated value in multiple places within a single expression, you can store that in a local variable.


2 Answers

I would capture the local environment,

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) 
like image 107
baptiste Avatar answered Oct 14 '22 14:10

baptiste


Here's an alternative that allows you to pass in any value through the YMul argument without having to add it to the Data data.frame or to the global environment:

plotfunc <- function(Data, YMul = 2){     eval(substitute(         expr = {             ggplot(Data,aes(x=x,y=y*YMul)) + geom_line()         },          env = list(YMul=YMul)))     }  plotfunc(xy, YMul=100) 

To see how this works, try out the following line in isolation:

substitute({ggplot(Data, aes(x=x, y=y*YMul))}, list(YMul=100)) 
like image 33
Josh O'Brien Avatar answered Oct 14 '22 14:10

Josh O'Brien