setMethod(“$< - ”)和set setReplaceMethod(“$”)之间有什么区别?

时间:2014-06-16 22:12:33

标签: r s4

问题

使用 OOP系统在进行编程时,必须使用setReplaceMethod进行编程?我不知道&#39;将setMethod添加到函数名称时与<-的区别。 setMethod("$<-")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的方法更好。我有权利吗?

1 个答案:

答案 0 :(得分:10)

这是setReplaceMethod

的定义
> setReplaceMethod
function (f, ..., where = topenv(parent.frame())) 
setMethod(paste0(f, "<-"), ..., where = where)
<bytecode: 0x435e9d0>
<environment: namespace:methods>

它在名称上粘贴了“&lt; - ”,因此功能上等同于setMethod("$<-")。 setReplaceMethod传达了更多的语义含义。