r ggplot 对象可以存储在 S4 插槽中吗?

Can an r ggplot object be stored in an S4 slot?

我正在尝试将 ggplot 对象保存在 S4 插槽中。

考虑:

library(stats4)
library(ggplot2)

setClass("gginS4",
      contains = c("ggplot"),
      slots = c(
        p = "ggplot"))

允许通过 gginS4@p 访问 ggplot。我已经将这种方法用于其他 类 数据(即“sf”等),没有问题。但是,上面的示例会产生以下错误:

Error in reconcilePropertiesAndPrototype(name, slots, prototype, superClasses,  : 
  no definition was found for superclass “ggplot” in the specification of class “gginS4”

ggplot2::ggplot() 创建的对象有两个 类 ggggplot,但是 setClass() 找不到这两个超类的定义。有没有其他方法来定义插槽?

让我们更深入地了解导致这种情况的原因

library(ggplot2)
isS3method("ggplot") # FALSE ,it means it is an S3 generic for more details: ?isS3method

您正在尝试创建一个 ggplot 通用插槽,它是使用 S3 OO 系统实现的,因此它将无法工作,因为两者之间不兼容 systems.To 将其存储在 S4 插槽中,使用 setOldClass.

setOldClass:注册一个老式的(a.k.a.‘S3’)class作为正式定义的class.

所以最终代码应该是这样的

library(ggplot2)
setOldClass(c("gg", "ggplot"))
setClass("gginS4",contains = "ggplot",
         slots = c(p = "ggplot"))