Reputation: 165
I created a function to return a ggplot object like below
uni_var<-function(df,col){
return(ggplot(df,aes(col))+geom_bar())
}
When I called on the mtcars data frame
uni_var(mtcars,cyl)
I get the below error
Error in FUN(X[[i]], ...) : object 'cyl' not found
In addition: Warning message:
In FUN(X[[i]], ...) : restarting interrupted promise evaluation
What is wrong with the my function ?
Upvotes: 2
Views: 333
Reputation: 2609
Nothing wrong with it. Just do:
uni_var(mtcars, "cyl")
Is this what you are going for?
uni_var<-function(df, col){
col <- eval(substitute(col), df)
return(ggplot(df, aes(col)) + geom_bar())
}
uni_var(mtcars, cyl)
Upvotes: 1
Reputation: 3175
It might be useful to study why you need the quotes as exemplified in @claudiu-papasteri's answer. Search for non-standard evaluation in R. Take a look also at https://rlang.r-lib.org/index.html.
Try figure why this example works:
library(ggplot2)
uni_var<-function(df,col){
col <- rlang::enquo(col)
return(ggplot(df,aes(!!col))+geom_bar())
}
uni_var(mtcars, cyl)
Upvotes: 4