デフォルト引数

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関数入門

Let's practice!

R関数入門

Preparing Video For Download...