【问题标题】:Custom plotting function error R - Error in FUN(X[[i]], ...) : object 'Species' not found自定义绘图函数错误 R - FUN 中的错误(X[[i]],...):找不到对象“物种”
【发布时间】:2021-09-16 10:35:57
【问题描述】:

我正在尝试编写一个函数来输出要在多个标准化数据帧上使用的图。 我一直在努力思考我做错了什么,但我无法弄清楚。

# function to plot 
plotify <- function(data, x, y){
      
  ggplot2::ggplot(data, aes(x, y)) + 
            geom_bar(stat = "identity")
} 

plotify(iris, Species, Sepal.Length)

## Error in FUN(X[[i]], ...) : object 'Species' not found

上面的代码是怎么给我报错的,但是如果要运行下面的代码,

ggplot(iris, aes(Species, Sepal.Length)) + geom_bar(stat = "identity")

我得到了我需要的地块?我在编写函数时是怎么搞砸的?

【问题讨论】:

    标签: r function ggplot2


    【解决方案1】:

    大约是non-standard evaluation。在这里,您可以使用curly-curly 使其工作

    plotify <- function(data, x, y){
      
      ggplot2::ggplot(data, ggplot2::aes({{ x }}, {{ y }})) + 
        ggplot2::geom_bar(stat = "identity")
    } 
    
    plotify(iris, Species, Sepal.Length)
    

    【讨论】:

    • 非常感谢!一定要阅读非标准评估!