Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

r - Object not found error with 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...