←
PDF 307 / 520 - In mean(), the data is x, and the details are how much data to trim from the ends (trim) and h
→
English · PDF 307
Original PDF page 307
中文 · PDF 307
  • 在 mean() 中,数据是 x,细节参数是从两端修剪多少数据(trim)以及如何处理缺失值(na.rm)。
  • 在 t.test() 中,数据是 x 和 y,检验的细节参数是 alternative、mu、paired、var.equal 和 conf.level。
  • 在 str_c() 中,你可以向 ... 提供任意数量的字符串,拼接的细节由 sep 和 collapse 控制。

一般来说,数据参数应放在最前面。细节参数应放在末尾,并且通常应有默认值。你以使用命名参数调用函数的相同方式指定默认值:

# 使用正态近似计算均值的置信区间 # 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.498 0.610 mean_ci(x, conf = 0.99) #> [1] 0.480 0.628

默认值几乎总是应该是最常用的值。这条规则的少数例外与安全性有关。例如,na.rm 默认为 FALSE 是合理的,因为缺失值很重要。尽管 na.rm = TRUE 是你通常在代码中设置的值,但默认情况下静默忽略缺失值是个坏主意。

当你调用函数时,通常可以省略数据参数的名称,因为它们非常常用。如果你要覆盖细节参数的默认值,则应使用完整名称:

# 好 mean(1:10, na.rm = TRUE) # 坏 mean(x = 1:10, , FALSE) mean(, TRUE, x = c(1:10, NA))