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.
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?
It works using ensym() (n.b. I also reordered group_by(!!nest, !!group) just so it matched the order in your example with group_by(carb, am)). I also named the arguments for the function at the end, since it's atypical to not have data in the first position (though that's obviously just a matter of choice).
That's a tricky one. I see why this is happening but I don't know how to explain it concisely and unfortunately I don't see a great way for users to determine when they have to unquote symbols rather than quosured symbols.
I can only tell you that quosures should work almost all the time, and that if your inputs represent data frame columns rather than complex expressions, it's safe to use ensym() and ensyms() instead.