This is a two part Question. I want to set the value of a prototype s4 object based on a different slots value and alternatively I want to implement this as a method.
I have an object I am trying to create. It has some slots. I would like to set a slots value based on the values put in from another slot. This is a simplified version of what I want to do.
i.e.,
setClass("Person",
representation(name = "character", age = "numeric", doubleAge = "numeric"),
prototype(name = "Bob", age = 5, doubleAge = 10) )
now I want to create an object but have the doubleAge value set itself based on the age slot.
p1 <- new("Person", name = "Alice", age = 6)
I see
An object of class "Person"
Slot "name":
[1] "Alice"
Slot "age":
[1] 6
Slot "doubleAge":
[1] 10
but I want to see doubleAge be 12. In the prototype, I do not know how to change doubleAge = 10
to something like doubleAge = 2*age
So as a solution I tried to make a setting function init
which sets the value after creation. This is the part 2 question.
setGeneric("init", "Person", function(object) {
standardGeneric("init")
}
setMethod("init","Person", function(object) {
object@doubleAge <- object@age*2
object
}
if I print object@doubleAge
in the method it returns 12 but it seems that the scope ends because it is 10 when it returns
Currently what works is very similar but it is not correct.
setGeneric("init<-", "Person", function(object) {
standardGeneric("init<-")
}
setMethod("init<-","Person", function(object) {
object@doubleAge <- object@age*2
object
}
but then I have to call like init(p1) <- NULL
which just seems weird. I know this example seems trivial but it is just a barebones example of a more complicated real world problem.