I am trying to pass column name as argument to a function which uses dplyr functions within.
There were multiple questions already asked around this theme and I tried all of them, everything seems to throw some or the other error.
I used enquo with !! as given here. Tried using !! as_label to combat the error I got from the previous step using this. Also tried to use group_by_ instead of group_by as mentioned here. I have also tried the curly operator for resolution
userMaster <- structure(list(user_id = c(1, 2, 3, 4, 5), city = structure(c(5L,
5L, 8L, 9L, 10L), .Label = c("Austin", "Boise", "Boston", "Chicago",
"Dallas", "Denver", "Detroit", "Kansas City", "Las Vegas", "Los Angeles",
"Manhattan", "Miami", "Minneapolis", "New York City", "Oklahoma City",
"Omaha", "Phoenix", "Saint Louis", "San Francisco", "Washington DC"
), class = "factor"), source = structure(c(2L, 2L, 2L, 2L, 2L
), .Label = c("Adwords", "Organic", "Search Ads"), class = "factor")), row.names = c(NA,
5L), class = "data.frame")
userCount <- function(table, metric){
col_enquo <- enquo(metric)
summary <- table %>% select(!! (col_enquo), source, user_id) %>%
group_by_(!! (col_enquo), source) %>% summarise(users = n_distinct(user_id)) %>%
left_join(table %>% group_by(source) %>%
summarise(total = n_distinct(user_id))) %>% mutate(users/total)
return(summary)
}
genderDemo <- userCount(userMaster, city)
I get every type of error -
Error: `quos(desire)` must evaluate to column positions or names, not a list
Error in !as_label(col_enquo) : invalid argument type
Error: Quosures can only be unquoted within a quasiquotation context.
# Bad:
list(!!myquosure)
# Good:
dplyr::mutate(data, !!myquosure)