对象未找到ggplot2错误 [英] Object not found error with ggplot2

查看:506
本文介绍了对象未找到ggplot2错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解这一点。

这些示例正在运行:

 #函数geom_density 

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


gr.den(sum.Empl)

#geom_point示例

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

然后我试着用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)

$ b gr.sc(sum.All,sum.Empl)

An d我收到这个错误。为什么?

  get(var.name.1)中的错误:找不到对象'var.name.1'


解决方案

如果您打算在函数中使用aes,最好使用

  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


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

解决方案

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

这篇关于对象未找到ggplot2错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆