how to set value in S4 object r using a method (no input value needed)

It seems overriding the initialize method worked for me. For example

setClass("Person",
         representation(name = "character", age = "numeric", doubleAge = "numeric"),
         prototype(name = "Bob", age = 5, doubleAge = 10) )

setMethod("initialize", "Person", function(.Object, ...) {
  .Object <- callNextMethod()
  .Object@doubleAge <- .Object@age*2
  .Object
})

(p1 <- new("Person", name = "Alice", age = 6))
# An object of class "Person"
# Slot "name":
# [1] "Alice"
# Slot "age":
# [1] 6
# Slot "doubleAge":
# [1] 12

The callNextMethod() runs the "default" initializer to set up all the values that we are not messing with. Then we just change the values we want and return the updated object.

Tags:

Oop

R

S4