原生泛型的方法查找

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 面向对象编程

Passons à la pratique !

R 中的 S3 与 R6 面向对象编程

Preparing Video For Download...