Reputation: 6615
I'm struggling to understand the issues with passing in arguments from a function into an R function. I normally am able to get this to work just fine by doing !!rlang::sym(argument).
What I'm trying to do is create a function that lets me customize which column in a dataset I want to do a given comparison calculation count on.
For example, I might want to count the number of values equal to 9999 or greater than 5, or maybe less than or equal to 5. This column could change as well.
custom_count=function(dataset, expr){
result=dataset %>% summarise( sum( !!rlang::sym(expr), na.rm = TRUE))
return(result)
}
custom_count(mtcars, 'mpg > 10')
custom_count( mtcars, 'vs==0')
However, these don't work. Is there anyway for me to pass in this combination of field + comparison sign+ value at the same time?
Upvotes: 0
Views: 983
Reputation: 47310
You want to use enexpr
because you're passing an expression, not a symbol :
library(dplyr)
custom_count=function(dataset, expr){
result=dataset %>% summarise( sum( !!rlang::enexpr(expr), na.rm = TRUE))
return(result)
}
custom_count(mtcars, mpg > 10)
# sum(mpg > 10, na.rm = TRUE)
# 1 32
custom_count( mtcars, vs==0)
# sum(vs == 0, na.rm = TRUE)
# 1 18
Upvotes: 1
Reputation: 1103
This seems to work for me.
custom_count=function(dataset, expr){
result=dataset %>% summarise( sum( !!expr, na.rm = TRUE))
return(result)
}
custom_count(mtcars, quote(mpg > 10))
Upvotes: 0