11.3 函数参数

函数的参数通常分为两大类,一组是提供要计算的参数,另外一组提供计算时的细节参数.

mean_ci <- function(x, conf = 0.95) {
  se <- sd(x) / sqrt(length(x))
  alpha <- 1 - conf
  mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2))
}
x <- runif(100)
mean_ci(x)
#> [1] 0.431 0.543
mean_ci(x, conf = 0.99)
#> [1] 0.414 0.560

11.3.1 参数名称

参数的名称很重要,方便我们理解参数含义,调用时不会混乱.以下时几个重要的参数名称

  • x, y, z: vectors.
  • w: a vector of weights.
  • df: a data frame.
  • i, j: numeric indices (typically rows and columns).
  • n: length, or number of rows.
  • p: number of columns.

11.3.2 检查参数值

在写函数时,并不清楚最终函数的输出,在编写函数时进行约束是有必要的.

wt_mean <- function(x, w) {
  if (length(x) != length(w)) {
    stop("`x` and `w` must be the same length", call. = FALSE)
  }
  sum(w * x) / sum(w)
}

11.3.3 …参数

R中的许多函数都能接受任意数量的输入:

sum(1,2,3,4,5,6,7,8,9,10)
#> [1] 55
stringr::str_c('a','b','d','e','f','g','h')
#> [1] "abdefgh"

下面的例子中

commas <- function(...) stringr::str_c(..., collapse = ", ")
commas(letters[1:10])
#> [1] "a, b, c, d, e, f, g, h, i, j"
#> [1] "a, b, c, d, e, f, g, h, i, j"

rule <- function(..., pad = "-") {
  title <- paste0(...)
  width <- getOption("width") - nchar(title) - 5
  cat(title, " ", stringr::str_dup(pad, width), "\n", sep = "")
}
rule("Important output")
#> Important output -----------------------------------------------------------