タイトルの内容についてのメモ書き。
コンソールでぱぱっと確認しようとしてちょいちょい忘れてしまうんで。今回はdplyr::recode
を例に。
まずは関数名だけで実行してみる:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
recode
#> function (.x, ..., .default = NULL, .missing = NULL)
#> {
#> UseMethod("recode")
#> }
#> <environment: namespace:dplyr>
こんな感じでUseMethod("hoge")
ってなってるとジェネリック関数で、class
が何によるかで関数が分かれていくことになる。じゃあどんなmethodがあるかを確認。
methods("recode")
#> [1] recode.character* recode.factor* recode.numeric*
#> see '?methods' for accessing help and source code
methods
関数に放り込むと、(関数名).(クラス名)
で定義された関数の一覧が返ってくる。それぞれのコードをコンソールでチェックするには、getS3method
関数を利用。
getS3method("recode", "character")
#> function (.x, ..., .default = NULL, .missing = NULL)
#> {
#> values <- list(...)
#> if (!all(has_names(values))) {
#> stop("All replacements must be named", call. = FALSE)
#> }
#> n <- length(.x)
#> template <- find_template(..., .default, .missing)
#> out <- template[rep(NA_integer_, n)]
#> replaced <- rep(FALSE, n)
#> for (nm in names(values)) {
#> out <- replace_with(out, .x == nm, values[[nm]], paste0("`",
#> nm, "`"))
#> replaced[.x == nm] <- TRUE
#> }
#> .default <- validate_recode_default(.default, .x, out, replaced)
#> out <- replace_with(out, !replaced & !is.na(.x), .default,
#> "`.default`")
#> out <- replace_with(out, is.na(.x), .missing, "`.missing`")
#> out
#> }
#> <environment: namespace:dplyr>
これでOK.