使用r OOP系统在s4进行编程时,必须使用setReplaceMethod
进行编程?我不知道'将setMethod
添加到函数名称时与<-
的区别。 setMethod("$<-")
和setReplaceMethod("$")
是否相同?
?setReplaceMethod
或??setReplaceMethod
的文档中找不到任何内容。除了用法之外什么也没有。roxygen2
来记录用setReplaceMethod
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
的方法更好。我有权利吗?
答案 0 :(得分:10)
这是setReplaceMethod
的定义> setReplaceMethod
function (f, ..., where = topenv(parent.frame()))
setMethod(paste0(f, "<-"), ..., where = where)
<bytecode: 0x435e9d0>
<environment: namespace:methods>
它在名称上粘贴了“&lt; - ”,因此功能上等同于setMethod("$<-")
。 setReplaceMethod传达了更多的语义含义。