【发布时间】:2014-06-16 22:12:32
【问题描述】:
问题
当使用s4 OOP 系统在r 中编程时,何时必须使用setReplaceMethod? 我看不出添加@987654328 时与setMethod 有什么区别@ 到函数的名称。 setMethod("$<-") 和 setReplaceMethod("$") 是否相等?
文档
- 我没有在
?setReplaceMethod或??setReplaceMethod的文档中找到任何内容。除了用法,别无其他。 - 在 StackOverflow 中,有 several questions about setReplaceMethod 但没有任何帮助。当我看到似乎是not possible to use
roxygen2来记录使用setReplaceMethod创建的方法时,我开始搜索这个问题的答案 - 我没有找到searching in r-project.org 的任何内容
可重现的例子
library(methods)
# Create a class
setClass("TestClass", slots = list("slot_one" = "character"))
# Test with setMethod -----------------------
setMethod(f = "$<-", signature = "TestClass",
definition = function(x, name, value) {
if (name == "slot_one") x@slot_one <- as.character(value)
else stop("There is no slot called",name)
return(x)
}
)
# [1] "$<-"
test1 <- new("TestClass")
test1$slot_one <- 1
test1
# An object of class "TestClass"
# Slot "slot_one":
# [1] "1"
# Use setReplaceMethod instead -----------------------
setReplaceMethod(f = "$", signature = "TestClass",
definition = function(x, name, value) {
if (name == "slot_one") x@slot_one <- as.character(value)
else stop("There is no slot called",name)
return(x)
}
)
# An object of class "TestClass"
# Slot "slot_one":
# [1] "1"
test2 <- new("TestClass")
test2$slot_one <- 1
test2
# [1] "$<-"
# See if identical
identical(test1, test2)
# [1] TRUE
实际结论
setReplaceMethod 似乎只允许在创建 set 方法时避免使用 <-。因为roxygen2 无法记录生成的方法,所以目前最好使用setMethod。我有权利吗?
【问题讨论】: