11.3 函数参数
函数的参数通常分为两大类,一组是提供要计算的参数,另外一组提供计算时的细节参数.
<- function(x, conf = 0.95) {
mean_ci <- sd(x) / sqrt(length(x))
se <- 1 - conf
alpha mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2))
}<- runif(100)
x 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 检查参数值
在写函数时,并不清楚最终函数的输出,在编写函数时进行约束是有必要的.
<- function(x, w) {
wt_mean 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
::str_c('a','b','d','e','f','g','h')
stringr#> [1] "abdefgh"
下面的例子中
<- function(...) stringr::str_c(..., collapse = ", ")
commas 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"
<- function(..., pad = "-") {
rule <- paste0(...)
title <- getOption("width") - nchar(title) - 5
width cat(title, " ", stringr::str_dup(pad, width), "\n", sep = "")
}rule("Important output")
#> Important output -----------------------------------------------------------