library(methods)
# Create a class
setClass(
Class = "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
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.