这是我发现的。正如@Hong Ooi 在评论中指出的setReplaceMethod("fun")
是相同的setMethod("fun<-")
, so setReplaceMethod
用于在 R 的 S4 对象系统中创建通用替换函数的方法。
什么是替换函数解释于r 中的替换函数是什么 https://stackoverflow.com/questions/11563154/what-are-replacement-functions-in-r。非常粗略地说,如果你有一个名为fun<-
,因为它的名字以<-
, 你可以写fun(x)<-a
R 会读到x <- "fun<-"(x,a)
.
S4 对象系统描述于S4 - 高级 R http://adv-r.had.co.nz/S4.html.
举个例子,也许从为 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
请注意参数x
, name
and value
由通用决定。