Question

How to change the folowing behavior, so that the slot name in object b and c points to the same object a?

A<-setClass(Class = "A",
            slot = c(name = "character"
            )
)
B<-setClass(Class = "B",
            slot=c(name = "A"
         )
)


a<-A(name="abc")
b<-B(name=a)
c<-B(name=a)

b@name@name="ABC"
b@name@name==c@name@name
Was it helpful?

Solution

S4 classes have standard R copy-on-write semantics, which means that updating objects does not have side effects. For the kind of semantic you want, use reference classes as described on ?ReferenceClasses

NameRef <- setRefClass("NameRef", fields=c(name="character"))
A <- setClass("A", slots=c(nameRef="NameRef"))

and then

> a = b = A(nameRef=NameRef(name="abc"))
> a@nameRef$name = "ABC"
> a@nameRef$name == b@nameRef$name
[1] TRUE

Reference behavior will surprise your R user, no matter how familiar it is in other programming environments, so use with care.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top