9

I can not get my head around this.

These examples are working:

# Function with geom_density

gr.den <- function(var.name) {
  ggplot(results, aes(get(var.name), fill = name)) +
  geom_density(alpha = 0.2) +
  geom_vline(xintercept = tv[, var.name], color="red", size=1) +
  xlab(var.name)
}

gr.den("sum.Empl")

# Example with geom_point

ggplot(results, aes(sum.All, sum.Empl)) +
  geom_point(alpha = 1/5) +
  opts(aspect.ratio = 1) +
  facet_grid(. ~ name)

Then I am trying to create similar function using geom_point:

gr.sc <- function(var.name.1, var.name.2) {
  ggplot(results, aes(get(var.name.1), get(var.name.2))) +
  geom_point(alpha = 1/5) +
  opts(aspect.ratio = 1) +
  facet_grid(. ~ name)
}

gr.sc("sum.All", "sum.Empl")

And I am getting this error. Why?

Error in get(var.name.1) : object 'var.name.1' not found
1
  • 1
    please provide a reproducible example. It looks like we need the contents of results and tv to run your code. Run dput() and paste the results into your questions. Commented Apr 1, 2011 at 14:02

3 Answers 3

18

If you are going to use aes inside a function it's better to use aes_string instead.

gr.sc <- function(var.name.1, var.name.2) {
  ggplot(results, aes_string(x = var.name.1, y = var.name.2)) +
  geom_point(alpha = 1/5) +
  opts(aspect.ratio = 1) +
  facet_grid(. ~ name)
}

gr.sc("sum.All", "sum.Empl")

HTH

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! aes_string helps a lot. I found an error also in the first function gr.den and solved it by aes_string.
5

The error occurs because get is looking in the wrong environment (i.e., not inside the results data frame). You could explicitly specify the get(var.name.1, envir = results) but that would be ugly, awful code. Much better to use aes_string as Iselzer suggests.

Comments

1

I ran into problems similar to this: https://groups.google.com/forum/#!topic/ggplot2/_kKP4NNu3bc where aes_string does not work.

This might be resolved in later versions of ggplot2. But I'm using an older version of ggplot2 for compatibility reasons. A quick hack that worked for me was to set function parameters as global variables, i.e.

gr.sc <- function(var.name.1, var.name.2) {
    var.name.1 <<- var.name.1
    ...
    ggplot(...
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.