我对setReplaceMethod()的用法感到困惑。查看?setReplaceMethod并没有提供解释,而Google搜索没有帮助。

问题:请解释setReplaceMethod(),它的用法及其工作方式(最好是举个例子)。

最佳答案

这是我发现的。正如@Hong Ooi在评论中指出的setReplaceMethod("fun")setMethod("fun<-")相同,因此setReplaceMethod用于为R的S4对象系统创建通用替换函数的方法。

什么是替换功能在what-are-replacement-functions-in-r中进行了说明。非常麻烦的是,如果您有一个名为fun<-的函数,因为它的名称以<-结尾,则可以编写fun(x)<-a,而R会读取x <- "fun<-"(x,a)

S4对象系统在S4 - Advanced R中进行了描述。

举个例子,也许更容易通过为S4泛型函数创建一个方法来开始,该方法不是替代函数:

## Define an S4 class 'Polygon' and an object of this class
setClass("Polygon", representation(sides = "integer"))
p1 <- new("Polygon", sides = 33L)
## Define a generic S4 function 'sides'
sides <- function(object){ NA }
setGeneric("sides")
## sides returns NA
sides( p1 )
## Define a method for 'sides' for the class 'Polygon'
setMethod("sides", signature(object = "Polygon"), function(object) {
  object@sides
})
## Now sides returns the sides of p1
sides( p1 )

为通用替换函数创建方法类似于:
## Define a generic replacement function 'sides<-'
"sides<-" <- function(object, value){ object }
setGeneric( "sides<-" )
## The generic 'sides<-' doesn't change the object
sides( p1 ) <- 12L
sides( p1 )
## Define a method for 'sides<-' for the class 'Polygon',
## setting the value of the 'sides' slot
setMethod( "sides<-", signature(object = "Polygon"), function(object, value) {
  object@sides <- value
  object
})
## Now 'sides<-' change the sides of p1
sides( p1 ) <- 12L
sides( p1 )

您还询问了$<-。我的猜测是:x$name<-value解释为"$"(x,name)<-value,然后解释为x <- "$<-"(x,name,value)。请注意,已经定义了通用函数$<-(isGeneric("$<-")),因此我们仅为类Polygon定义一个方法:
setMethod( "$<-", signature(x = "Polygon"), function(x, name, value) {
  if( name=="sides" ){
    x@sides <- value
  }
  x
})
## Nothing changes if we try to set 'faces'
p1$faces <- 3L
p1
## but we can set the 'sides'
p1$sides <- 3L
p1

请注意,参数xnamevalue由泛型规定。

关于r - 什么是setReplaceMethod(),它如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49132422/

10-12 17:18