Search code examples
rr-s4roxygen2

setClassUnion fails joining a glm with a coxph class


When I try to create a class in R, containing a slot that should accept either a glm class object or a coxph class one I get an error during package build that is Error in setClassUnion(name = "glmORcoxph", members = c("glm", "coxph")) : the member classes must be defined: not true of "coxph". I tried to put @import, @importClassesFrom, @importFrom Roxygen directives to my source code but without success. This is the code I use for creating my DoseVolumeModel class:

setClassUnion(name = "ConfidenceInterval", members = c("NULL", "numeric"))
setClassUnion(name = "glmORcoxph", members = c("glm", "coxph"))
setClass("DoseVolumeModel", 
     representation(
       output.matrix = "matrix",
       fitted.model = "glmORcoxph",
       fitted.value = "numeric",
       CI = "ConfidenceInterval",
       fitted.parameter = "character"
     )
)

How can I fix it?


Solution

  • You can't use S3 classes like coxph unless they have been pre-registered. You can do this by calling

    setOldClass("coxph")
    

    before your calls to setClassUnion. Then you are free to use coxph as a class definition in slots or class unions.

    Note that you cannot guarantee much about such coxph objects as R does not enforce that they have any particular properties. Any user is free to do something like

    x <- 1
    class(x) <- "coxph"
    

    (or take a real coxph object and NULL out parts of it)

    and they will still be valid inputs to your classes. You might want to implement some input checking to take account of this.