R`+`运算符如何根据类而知道不同的行为?

Wil*_*hiu 2 r lubridate

这是lubridate包装中的一种方法。

> getMethod("month<-")
Method Definition (Class "derivedDefaultMethod"):

  function (x, value)
  {
    if (!is.numeric(value)) {
      value <- pmatch(tolower(value), c("january", "february",
                                        "march", "june", "july", "august", "september", "october",
                                        "november", "december"))
    }
    x <- x + months(value - month(x))
  }
Run Code Online (Sandbox Code Playgroud)

我的问题是+运算符的最后一行。运算符的行为取决于的类别x。R如何知道要这样做?我如何查看其源代码+

> library(lubridate)
> 
> customFUN <- function (x, value){
+   x <- x + months(value - month(x))
+   return(x)
+ }
> 
> 
> init_datePOSIX <- as.POSIXct("2017-11-01")
> init_dateDate <- as.Date("2017-11-01")
> 
> customFUN(init_datePOSIX, 12)
[1] "2017-11-01 PDT"
> customFUN(init_dateDate, 12)
[1] "2017-12-01"

Run Code Online (Sandbox Code Playgroud)

我的会话信息:

> sessionInfo()
R version 3.3.3 (2017-03-06)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: Red Hat Enterprise Linux

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] lubridate_1.7.1

loaded via a namespace (and not attached):
[1] magrittr_1.5  tools_3.3.3   yaml_2.2.0    Rcpp_1.0.0    stringi_1.3.2 stringr_1.3.1
Run Code Online (Sandbox Code Playgroud)

zac*_*dav 5

+运营商真的就像任何其他的功能,并能作这样的处理。

您可以+通过键入以下内容查看源代码:

`+`
Run Code Online (Sandbox Code Playgroud)

此外,您可以+通过键入以下命令查看各种方法:

methods(`+`)
Run Code Online (Sandbox Code Playgroud)

调用函数时,将检查对象的类以查看应调用的方法。当存在多个类时,第一个匹配方法将从这些类中获取。

因此,您可以定义自己的方法 +

`+.custom` <- function(e1, e2) {
  paste0(e1, e2)
}

x <- 1
class(x) <- c("custom", "numeric")

x + x
Run Code Online (Sandbox Code Playgroud)

在这里,我们覆盖了x要添加其他类的类"custom",您可以看到该行为默认为新定义的+.custom

但是,该值对于其他尚未定义的方法仍然可以正常使用(数字),请尝试以下代码:

x / 10 * 500
Run Code Online (Sandbox Code Playgroud)

其他阅读: https : //stat.ethz.ch/R-manual/R-patched/library/base/html/UseMethod.html

  • `help(“ groupGeneric”)`也很重要。 (2认同)