简体   繁体   English

具有可选默认参数和必需椭圆的dplyr函数

[英]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. 我希望n参数是可选的。 Ie if not explicitly defined (as my_n in the example above), I would like for the argument to take default n value. 即,如果未显式定义(如my_n的示例中的my_n ),则我希望该参数采用默认的n值。 As it would usually happen with n = "n" , which is now redundant due to attempted hasArgs() call. 就像通常在n = "n"发生的那样,由于尝试hasArgs()调用因此现在是多余的。

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. 您需要更改参数的顺序,以便您给定的第二个参数(如果未命名)不会被解释为n值。

add_tally <- function(df, ..., n = "n") {
 #function code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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