默认参数

R 函数编写入门

Richie Cotton

Data Evangelist at DataCamp

toss_coin() 的问题

toss_coin <- function(n_flips, p_head) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}

在签名中设置默认值

toss_coin <- function(n_flips, p_head = 0.5) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}
R 函数编写入门

带默认值的模板

my_fun <- function(data_arg1, data_arg2, detail_arg1 = default1) {
  # Do something
}
R 函数编写入门

其他类型的默认值

args(median)
function (x, na.rm = FALSE, ...)
library(jsonlite)
args(fromJSON)
function (txt, simplifyVector = TRUE, simplifyDataFrame = simplifyVector, 
    simplifyMatrix = simplifyVector, flatten = FALSE, ...)
R 函数编写入门

NULL 作为默认值

按约定,这表示:

函数会对该参数进行特殊处理。请阅读文档。

args(set.seed)
function (seed, kind = NULL, normal.kind = NULL)
R 函数编写入门

分类参数的默认值

  1. 在签名中传入字符向量。
  2. 在函数体中调用 match.arg()
args(prop.test)
function (x, n, p = NULL, alternative = c("two.sided", "less", "greater"), 
  conf.level = 0.95, correct = TRUE)

在函数体内

alternative <- match.arg(alternative)
R 函数编写入门

按分位数分箱向量

cut_by_quantile <- function(x, n, na.rm, labels, interval_type) {
  probs <- seq(0, 1, length.out = n + 1)
  quantiles <- quantile(x, probs, na.rm = na.rm, names = FALSE)
  right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
  cut(x, quantiles, labels = labels, right = right, include.lowest = TRUE)
}
  • x:要分箱的数值向量
  • n:将 x 分成的类别数
  • na.rm:是否移除缺失值?
  • labels:类别的字符标签
  • interval_type:区间左开还是右开?
R 函数编写入门

猫的心脏重量

猫心脏重量的条带图。范围为 3 到 20 克。

quantile(cats$Hwt)
    0%    25%    50%    75%   100% 
 6.300  8.950 10.100 12.125 20.500
1 data(cats, package = "MASS")
R 函数编写入门

按分位数分箱

上一页的条带图已着色:左侧为红色点,然后是绿色、青色,右侧为紫色。

cut(x, quantile(x))
R 函数编写入门

Passons à la pratique !

R 函数编写入门

Preparing Video For Download...