SHARE
TWEET

Untitled

a guest Jul 18th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. my_summarise() is a custom function that automatically choose between sym() and enquo() for input type "character" and ^quosure
  2.  
  3. ## This works!
  4. my_summarise <- function(df, var){
  5.   if(inherits(substitute(var), "character")){    
  6.     var = sym(var)
  7.   }
  8.   else if(inherits(substitute(var), "name")){
  9.     var = enquo(var)
  10.   }
  11.   df %>% summarise(avg = mean(!!var))
  12. }
  13.  
  14. identical(my_summarise(iris, Sepal.Length),
  15.           my_summarise(iris, 'Sepal.Length'))
  16.          
  17. # TRUE
  18.  
  19. ######################
  20.  
  21. ## Thought substitute() was equivalent to enquo() but it's not. Replacing substitute() with enquo()
  22.  
  23. my_summarise2 <- function(df, var){
  24.   if(inherits(enquo(var), "character")){    
  25.     var = sym(var)
  26.   }
  27.   else if(inherits(enquo(var), "name")){
  28.     var = enquo(var)
  29.   }
  30.   df %>% summarise(avg = mean(!!var))
  31. }
  32.  
  33. identical(my_summarise2(iris, Sepal.Length),
  34.           my_summarise2(iris, 'Sepal.Length'))
  35.          
  36. # object 'Sepal.Length' not found
  37.  
  38. #####################
  39.  
  40. ## Replacing enquo() with enexpr() WORKS !
  41. my_summarise3 <- function(df, var){
  42.   if(inherits(enexpr(var), "character")){    
  43.     var = sym(var)
  44.   }
  45.   else if(inherits(enexpr(var), "name")){
  46.     var = enquo(var)
  47.   }
  48.   df %>% summarise(avg = mean(!!var))
  49. }
  50.  
  51. identical(my_summarise3(iris, Sepal.Length),
  52.           my_summarise3(iris, 'Sepal.Length'))
  53.          
  54. # TRUE
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top