I've a simple function that adds counts for unique combination of variables:
# Add tally summary for group
add_tally <- function(df, n = "n", ...) {
# Grpup variables
group_vars <- rlang::quos(...)
# Check if ellipsis is empty
if (length(group_vars) == 0) {
stop("Missing grouping variables")
}
none <- Negate(any)
# Check that passed object is data frame or tibble
if (none(tibble::is_tibble(df), is.data.frame(df))) {
stop("Passed object should be a data frame or tibble.")
}
if (hasArg("n")) {
# Take varname
varname <- n
} else {
varname <- "n"
}
df %>%
group_by(!!!group_vars, add = TRUE) %>%
mutate(!!varname := sum(n())) %>%
ungroup()
}
It's fairly straightforward:
>> mtcars[,c("am", "gear")] %>% add_tally(n = "my_n", am,gear)
# A tibble: 32 x 3
am gear my_n
<dbl> <dbl> <int>
1 1.00 4.00 8
2 1.00 4.00 8
3 1.00 4.00 8
4 0 3.00 15
5 0 3.00 15
6 0 3.00 15
7 0 3.00 15
8 0 4.00 4
9 0 4.00 4
10 0 4.00 4
I would like for the n
argument to be optional. I.e. if not explicitly defined (as my_n
in the example above), I would like for the argument to take default n
value. As it would usually happen with n = "n"
, which is now redundant due to attempted hasArgs()
call.
This fails:
>> mtcars[,c("am", "gear")] %>% add_tally(am,gear)
Error in add_tally(., am, gear) : object 'am' not found
# A tibble: 32 x 3
am gear n
<dbl> <dbl> <int>
1 1.00 4.00 8
2 1.00 4.00 8
3 1.00 4.00 8
4 0 3.00 15
5 0 3.00 15
6 0 3.00 15
7 0 3.00 15
8 0 4.00 4
9 0 4.00 4
10 0 4.00 4
You need to change the order of your parameters so the 2nd parameter you give isn't interpreted as the n
value if it's unnamed.
add_tally <- function(df, ..., n = "n") {
#function code
}