9

Question

When programming in with the 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

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?

Community
  • 1
  • 1
jomuller
  • 1,032
  • 2
  • 10
  • 19

1 Answers1

11

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.

Martin Morgan
  • 45,935
  • 7
  • 84
  • 112