When I modify parts of a duplicated Geom object, this also modifies the underlying original Geom. Why?
(Big big thanks to user Stefan to identify this problem via comment on a now deleted previous question of mine).
library(ggplot2)
GeomFunction$required_aes
#> [1] "x" "y"
GeomFunction2 <- GeomFunction
GeomFunction2$required_aes <- c("x", "y", "fun")
GeomFunction$required_aes
#> [1] "x" "y" "fun"
Created on 2022-01-09 by the reprex package (v2.0.1)
Because ggproto class objects are environments instead of list-like structures, as can be checked with
is.environment(GeomFunction). Environments do not follow the copy-on-modify heuristics that e.g. a vector adheres to.The correct way to make a copy for modification purposes is with the
ggprotoconstructor. Technically, you're making a child instance ofGeomFunction.Created on 2022-01-09 by the reprex package (v2.0.1)
In addition, because ggproto objects are environments, we can use
ls()to see what they contain.You can see that every layer in the hierarchy only contains the changes relative to the parent, and a mysterious
superobject, which is a function. When thesuperfunction is called, you can see that it retrieves the parent class.Created on 2022-01-09 by the reprex package (v2.0.1)
The absence of a
superobject inGeomsuggests thatGeomis the root class.The reason that the
ggprotoclass exists is to allow extensions to reuse large chunks of code, without having to build them from scratch. In theory, ggproto is similar to R6 or reference class object-oriented programming, but I think R6/reference classes had some drawbacks that wouldn't allow cross-package inheritance of their classes.