[Rd] Problem with _new_ if class "lm" in object representation.

John Chambers jmc at research.bell-labs.com
Wed Sep 29 20:16:11 CEST 2004


Wolski wrote:
> 
> Hi!
> Consider this code.
> 
> setClass("Ctest"
>         ,representation(
>                 test="character"
>                 ,bla="character"
>                 ,mod="lm"
>                 )
>         )
> 
> new("Ctest",test="bla")                     #This produces an error.
> 
> #Error in validObject(.Object) : Invalid "Ctest" object: Invalid object for slot "mod" in class "Ctest": got class "NULL", should be or extend class "lm"

And the error message is correct.  Since "lm" is an S3 class, there is
no way to generate an object automatically from it.  new("lm") will also
produce an error.

If you want objects to be generated from your class with a default "lm"
object, you have to first decide what that is.  Assuming you know, you
need to either put that element into the protoype for the class, or have
a method for initialize() that does something sensible, using the rest
of the data in the object.

The prototype solution could look something like:

R> lm0 = lm(1~1)
R> setClass("Ctest", representation(test = "character", 
    bla = "character", mod = "lm"), prototype=prototype(mod = lm0))
R> new("Ctest", test="bla")
An object of class "Ctest"
Slot "test":
[1] "bla"

Slot "bla":
character(0)

Slot "mod":

Call:
lm(formula = 1 ~ 1)

Coefficients:
(Intercept)  
          1  


There is no automatic relation between the class "lm" and the function
lm().  The green book recommends having a generator function, but the R
code can't assume this has been done.

> 
> setClass("Ctest"
>         ,representation(
>                 test="character"
>                 ,bla="character"
>                 ,mod="character"                # its the only with the class definition above.
>         )
>         )
> new("Ctest",test="bla")                         #this works as I would expect.
> 
> #An object of class "Ctest"
> #Slot "test":
> #[1] "bla"
> #
> #Slot "bla":
> #character(0)
> #
> #Slot "mod":
> #character(0)
> 
> Thought that this is due to that the class lm has no lm(0) object. Hence i tried
> 
> setClass("brum",representation(brum="brum"))
> setClass("Ctest"
>         ,representation(
>                 test="character"
>                 ,bla="character"
>                 ,mod="brum"                # its the only with the class definition above.
>         )
>         )
> 
> new("Ctest",test="best")  #but this works to.
> 
> ______________________________________________
> R-devel at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

-- 
John M. Chambers                  jmc at bell-labs.com
Bell Labs, Lucent Technologies    office: (908)582-2681
700 Mountain Avenue, Room 2C-282  fax:    (908)582-3340
Murray Hill, NJ  07974            web: http://www.cs.bell-labs.com/~jmc



More information about the R-devel mailing list