2

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 ?

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Excelent. Your are right, I think this is what he was after.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.