LoginSignup
3
4

More than 5 years have passed since last update.

Rのジェネリック関数のコードを確認

Posted at

タイトルの内容についてのメモ書き。

コンソールでぱぱっと確認しようとしてちょいちょい忘れてしまうんで。今回は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.

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4