简体   繁体   中英

Dplyr function with optional default argument and required ellipiss

I've a simple function that adds counts for unique combination of variables:

Function

# 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()

}

Example

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

Problem

I would like for the n argument to be optional. Ie 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.

Example

This fails:

>> mtcars[,c("am", "gear")] %>% add_tally(am,gear)
Error in add_tally(., am, gear) : object 'am' not found

Desired results

# 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM