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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With