Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object not found error with ggplot2

Tags:

r

ggplot2

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
like image 492
djhurio Avatar asked Apr 01 '11 13:04

djhurio


People also ask

Why is object not found in R?

This error usually occurs for one of two reasons: Reason 1: You are attempting to reference an object you have not created. Reason 2: You are running a chunk of code where the object has not been defined in that chunk.

What is a Ggplot object?

In a ggplot object, layers reside in a list, and their positions in the list determine the plotting order when generating the graphical output. The grammar of graphics treats the list of layers as a stack using only push operations.


1 Answers

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.

like image 174
Richie Cotton Avatar answered Oct 15 '22 10:10

Richie Cotton