原始泛型的方法查找

在 R 中使用 S3 與 R6 的物件導向程式設計

Richie Cotton

Data Evangelist at DataCamp

 

  • 撰寫程式碼
  • 偵錯程式碼
  • 維護程式碼

 

  • 執行程式碼
在 R 中使用 S3 與 R6 的物件導向程式設計

R vs. C

  • C 程式常跑得更快
  • R 程式通常較容易撰寫
  • 也更容易偵錯
在 R 中使用 S3 與 R6 的物件導向程式設計

ch2_3-method-lookup-for-primitive-generics.012.png

在 R 中使用 S3 與 R6 的物件導向程式設計

ch2_3-method-lookup-for-primitive-generics.013.png

在 R 中使用 S3 與 R6 的物件導向程式設計
exp
function (x)  .Primitive("exp")
+
function (e1, e2)  .Primitive("+")
if
.Primitive("if")
sin
function (x)  .Primitive("sin")
-
function (e1, e2)  .Primitive("-")
for
.Primitive("for")
在 R 中使用 S3 與 R6 的物件導向程式設計
.S3PrimitiveGenerics
"anyNA"          "as.character"   "as.complex"
"as.double"      "as.environment" "as.integer"     
"as.logical"     "as.call"        "as.numeric"
"as.raw"         "c"              "dim"           
"dim<-"          "dimnames"       "dimnames<-"     
"is.array"       "is.finite"      "is.infinite"    
"is.matrix"      "is.na"          "is.nan"
"is.numeric"     "length"         "length<-"      
"levels<-"       "names"          "names<-"
"rep"            "seq.int"        "xtfrm" 
在 R 中使用 S3 與 R6 的物件導向程式設計
all_of_time <- c("1970-01-01", "2012-12-21")
as.Date(all_of_time)
"1970-01-01" "2012-12-21"
class(all_of_time) <- "date_strings"
as.Date(all_of_time)
Error in as.Date.default(all_of_time) : 
  do not know how to convert 'all_of_time' to class"Date"
length(all_of_time)
2
在 R 中使用 S3 與 R6 的物件導向程式設計

重點整理

  • 有些 R 函式其實是用 C 撰寫
  • primitive 介面可達到最佳效能
  • .S3PrimitiveGenerics 列出原始的 S3 泛型
  • 原始泛型在找不到方法時不會拋出錯誤
在 R 中使用 S3 與 R6 的物件導向程式設計

一起來練習吧!

在 R 中使用 S3 與 R6 的物件導向程式設計

Preparing Video For Download...