Home > Software design >  Custom plotting function error R - Error in FUN(X[[i]], ...) : object 'Species' not found
Custom plotting function error R - Error in FUN(X[[i]], ...) : object 'Species' not found

Time:09-17

I'm trying to write a function that outputs plots to be used over multiple standardized dataframes. I've been trying to wrap my head around what I'm doing wrong and I can't figure it out.

# 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

How does the above code throw me an error but if were to run the following code,

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

I get the plots I need? How have I screwed up in writing the function?

CodePudding user response:

It is about non-standard evaluation. Here, you can use curly-curly to make it work

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

plotify(iris, Species, Sepal.Length)
  • Related