Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

s4

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?

like image 735
jomuller Avatar asked Jun 16 '14 22:06

jomuller


1 Answers

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.

like image 97
Martin Morgan Avatar answered Sep 28 '22 14:09

Martin Morgan