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