【问题标题】:Can an r ggplot object be stored in an S4 slot?r ggplot 对象可以存储在 S4 插槽中吗?
【发布时间】:2021-03-02 01:09:50
【问题描述】:

我正在尝试将 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() 找不到这两个超类的定义。是否有另一种方法来定义插槽?

【问题讨论】:

    标签: r ggplot2 s4


    【解决方案1】:

    让我们深入挖掘一下以了解造成这种情况的原因

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

    您正在尝试创建一个ggplot generic 的插槽,该插槽是使用 S3 OO 系统实现的,因此由于两个系统之间的不兼容,它将无法工作。要将其存储在 S4 插槽中,请使用 setOldClass

    setOldClass:将旧式(又名“S3”)类注册为正式定义的类。

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

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

    【讨论】:

    • ggplot 是一个 generic,因此显然不是 S3 或 S4 对象。但是,您是对的,您需要调用 setOldClass 才能在 S4 对象中使用 S3 对象
    猜你喜欢
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多