3

I have a sample data below

data <- data.frame(yr = c(1999, 2000, 2001, 2002, 2003, 2004, 2005,
                          2006, 2007, 2009, 2010, 2011, 2012), 
                   ntemp =c (11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 12, 23))

When I try running this function, to access the variable inside a ggplot function.

FUN <- function(data, fun.y, yr) {
      fun.data <- data     
      ggplot(fun.data, aes(yr, fun.y)) +
      geom_point() +
      scale_y_continuous(fun.y)    
    }
    
FUN(data, "ntemp", yr)

I get an Error in eval(expr, envir, enclos) : object 'fun.y' not found

How can I solve this?

Waldi
  • 39,242
  • 6
  • 30
  • 78
Keniajin
  • 1,649
  • 2
  • 20
  • 43
  • You are trying to map `fun.y`, which is supposed to be a variable in `fun.data`. Since it is not, you get an error. – tonytonov Jan 20 '14 at 09:47
  • I have passed fun.y in the function as ntemp – Keniajin Jan 20 '14 at 09:50
  • ```aes_string()``` is the way. If you would be interested in adding facets, here is a [question that migth help](http://stackoverflow.com/questions/19016007/metaprogramming-with-ggplot2). – marbel Jan 20 '14 at 10:06
  • If the proposed solution works for you, please do not forget to mark question as accepted. – tonytonov Jan 20 '14 at 10:23

1 Answers1

3

aes only looks at the variables in data argument. If you would like to pass variable as an argument to FUN by its character name, use aes_string:

FUN <- function(data, x, y) {
  ggplot(data, aes_string(x=x, y=y)) + geom_point()
}

FUN(data, y="ntemp", x="yr")

A small correction: variable inside aes call should be defined in the scope where the ggplot object is evaluated, so technically a variable is looked up in data first, then in global environment (by default). See this and this questions.

Community
  • 1
  • 1
tonytonov
  • 25,060
  • 16
  • 82
  • 98