创建一个S4超类 - 带代码示例

时间:2013-10-27 22:11:32

标签: r s4

好的,我花了一些时间来创建一个代码片段来复制我的问题。这里是。请注意,如果您运行命令new("FirstSet", id = "Input", multiplier = 2) 你会得到正确的答案。但是,如果您尝试创建包含两者的类,您将获得以下内容:Error in .local(.Object, ...) : argument "id" is missing, with no default。这实际上是我能解释/显示问题的最佳方法。

世界上我做错了什么?

setClass("Details",
     representation(
      ID = "character",
      Anumber = "numeric"))

 Input <- new("Details",
         ID = "Input",
         Anumber = 2)

 setClass("FirstSet",
     representation(
     Anothernumber = "numeric"))

 setGeneric(
 name = "FirstSet",
 def = function(object){standardGeneric("FirstSet")}
 )

 setMethod("initialize",
      signature(.Object = "FirstSet"),
      function (.Object, id, multiplier) 
      { x = id@Anumber
        y = x * multiplier

        .Object@Anothernumber = y
        return(.Object)
      }
 )

setClass("Super", contains = c("Details", "FirstSet"))  

更正后的代码现在会出现一个新错误。我按照帖子中的说明解决了我的问题。我还为“超级”创建了一个通用和方法,请参阅下面的代码。现在,我收到一个新错误。 .local(.Object,...)中的错误:尝试从没有插槽的基本类(“字符”)的对象获取插槽“Anumber”。伙计,这太累了,我以为我拥有它。

详细信息的目标是,将有许多文件被序列化,并且根据文件中数据的特征调用方法。这在R中是否可能,或者我试图做一些R不能做的事情?

新代码

setClass("Details",
representation(
    ID = "character",
    Anumber = "numeric"))

setGeneric("Details",
def = function(object){standardGeneric("Details")})

setMethod("initialize",
signature(.Object = "Details"),
function(.Object, ID = character(), Anumber = numeric()){
    .Object@ID = ID
    .Object@Anumber = 2
    return(.Object)
 })

setClass("FirstSet",
representation(
    Anothernumber = "numeric"))

setGeneric(
name = "FirstSet",
def = function(object){standardGeneric("FirstSet")}
)

 setMethod("initialize",
signature(.Object = "FirstSet"),
function (.Object, id = character(), multiplier = numeric()) 
{ x = id@Anumber
    y = x * multiplier

    .Object@Anothernumber = y
    return(.Object)
}
)

setClass("Super", contains = c("Details", "FirstSet"))

setGeneric("Super",
def = function(object){standardGeneric("Super")})

  setMethod("initialize",
  signature(.Object = "Super"),
  function(.Object, id = character(), Anumber = numeric()){
    Details <- new("Details", ID = id, Anumber = Anumber)
    FirstSet <- new("FirstSet", Anothernumber = Anothernumber)
    Super <- new("Super", Details, FirstSet)
    return(.Object)
 })

1 个答案:

答案 0 :(得分:1)

基本规则是new("FirstSet")(或任何非虚拟类)需要工作。你没有(因为intiailize参数没有默认值)。有关更多指南,请参阅this answer