【问题标题】:What's the difference between setMethod("$<-") and set setReplaceMethod("$")?setMethod("$<-") 和 set setReplaceMethod("$") 有什么区别?
【发布时间】:2014-06-16 22:12:32
【问题描述】:

问题

当使用 OOP 系统在 中编程时,何时必须使用setReplaceMethod? 我看不出添加@987654328 时与setMethod 有什么区别@ 到函数的名称。 setMethod("$&lt;-") 和 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 方法时避免使用 &lt;-。因为roxygen2 无法记录生成的方法,所以目前最好使用setMethod。我有权利吗?

【问题讨论】:

    标签: r s4 r s4


    【解决方案1】:

    这里是setReplaceMethod的定义

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

    它在名称上粘贴“setMethod("$<-")。 setReplaceMethod 传达了更多的语义含义。

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 2021-11-25
      • 2016-08-08
      • 2013-04-19
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      相关资源
      最近更新 更多