What's the difference between setMethod(“$<-”) and set setReplaceMethod(“$”)?

主宰稳场 提交于 2019-11-30 03:34:48

问题


Question

When programming in r with the s4 OOP system, when one have to use setReplaceMethod? I don't see what's the difference with the setMethod when adding <- to the name of the function. Does setMethod("$<-") and setReplaceMethod("$") are equal?

Documentation

  • I didn't find anything in the documentation with ?setReplaceMethod or ??setReplaceMethod. There is nothing except the usage.
  • In StackOverflow, there is several questions about setReplaceMethod but none helping. I started to search a answer to this question when I saw it seem's is not possible to use roxygen2 to document methods created with setReplaceMethod
  • I didn't find anything by searching in r-project.org

Reproductible example

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

Actual conclusion

setReplaceMethod seems only to permit to avoid the <- when creating a set method. Because roxygen2 can't document methods produced with, it's better for the moment to use setMethod. Does I have right?


回答1:


Here's the definition of setReplaceMethod

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

It is pasting a "<-" on to the name, so is functionally equivalent to setMethod("$<-"). setReplaceMethod conveys more semantic meaning.



来源:https://stackoverflow.com/questions/24253048/whats-the-difference-between-setmethod-and-set-setreplacemethod

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!