I'm trying to write a general data summary function that keeps empty groups when summarizing data. I've been using the complete function to do this with hard-coded grouping and nesting variables, but when I try to implement this in a user-defined function, nesting() doesn't seem to work with quosures and tidy evaluation. I'm just curious if there's a way around this or if I need to use a different approach. Here's and example:
library(tidyverse)
d = mtcars %>%
mutate_at(vars(carb,am), as.factor)
d %>%
group_by(carb, am) %>%
tally %>%
complete(am, nesting(carb), fill=list(n=0))
The rows with n=0 are the additional rows added by complete to reflect combinations of am and carb that don't exist in the original data.
am carb n
<fct> <fct> <dbl>
1 0 1 3
2 1 1 4
3 0 2 6
4 1 2 4
5 0 3 3
6 1 3 0
7 0 4 7
8 1 4 3
9 0 6 0
10 1 6 1
11 0 8 0
12 1 8 1
But this approach fails if used in a function with quosures:
fnc = function(group, nest, data) {
group=enquo(group)
nest=enquo(nest)
data %>%
group_by(!!group, !!nest) %>%
tally %>%
complete(!!group, nesting(!!nest), fill=list(n=0))
}
fnc(am, carb, d)
Error in eval_tidy(xs[[i]], unique_output) : object 'carb' not found
Is there a way to make this approach work, or do I need to try some other method, like joining the original data with an expanded grid of group combinations?