Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- my_summarise() is a custom function that automatically choose between sym() and enquo() for input type "character" and ^quosure
- ## This works!
- my_summarise <- function(df, var){
- if(inherits(substitute(var), "character")){
- var = sym(var)
- }
- else if(inherits(substitute(var), "name")){
- var = enquo(var)
- }
- df %>% summarise(avg = mean(!!var))
- }
- identical(my_summarise(iris, Sepal.Length),
- my_summarise(iris, 'Sepal.Length'))
- # TRUE
- ######################
- ## Thought substitute() was equivalent to enquo() but it's not. Replacing substitute() with enquo()
- my_summarise2 <- function(df, var){
- if(inherits(enquo(var), "character")){
- var = sym(var)
- }
- else if(inherits(enquo(var), "name")){
- var = enquo(var)
- }
- df %>% summarise(avg = mean(!!var))
- }
- identical(my_summarise2(iris, Sepal.Length),
- my_summarise2(iris, 'Sepal.Length'))
- # object 'Sepal.Length' not found
- #####################
- ## Replacing enquo() with enexpr() WORKS !
- my_summarise3 <- function(df, var){
- if(inherits(enexpr(var), "character")){
- var = sym(var)
- }
- else if(inherits(enexpr(var), "name")){
- var = enquo(var)
- }
- df %>% summarise(avg = mean(!!var))
- }
- identical(my_summarise3(iris, Sepal.Length),
- my_summarise3(iris, 'Sepal.Length'))
- # TRUE
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement