'R: Why can one S4 object have multiple variable names?

If I assign an ordinary object to variable foo, and then foo <- bar, then foo and bar will be two separate objects. Then, if I eventually modify bar, foo will not be modified—and vice versa.

However, this is different with S4 objects. Specifically, if I modify the object assigned to bar, then all assignments of this object (here: also foo) will be affected. Here's one example:

foo <- openxlsx::createWorkbook()
openxlsx::addWorksheet(foo, "Sheet 1")
writeData(foo, sheet=1, x="Hi")

openxlsx::readWorkbook(foo)
# > Hi

bar <- foo
writeData(bar, sheet=1, x="Hello")
openxlsx::readWorkbook(foo)
# > Hello

Why did the S/R community consider this assignment practice to be useful, when the R language works quite differently when it comes to assignments?



Solution 1:[1]

Your assertion is false --- S4 objects in general do not exhibit this behaviour:

> cl <- setClass("test",slots=c(x="integer"))
> z1 <- cl(x=1L)
> z2 <- z1
> identical(z1,z2)
[1] TRUE
> z2@x <- 2L
> identical(z1,z2)
[1] FALSE

This behaviour is specific to the class of your foo and bar, and probably is to do with the fact that they are connections, which can be duplicated but ultimately are probably still connected to the same file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JDL