[R] Inheriting from factors + co.

Torsten Steuernagel Torsten.Steuernagel at gmx.de
Tue Feb 24 18:59:05 CET 2004


I'm trying to create a formal class that does the following:

1) accept objects of arbitrary class as .Data slot

2) provide a set of other slots that are of fixed type (as usual)

The following two approaches came to my mind:

A)

setClass("myclass", representation("ANY", x = "numeric", y 
="numeric"))

new("myclass", 1:10)		# works 
new("myclass", "Test")		# works
new("myclass", factor(1:10))	# fails

While I'm able to specify any object that has a formal class as data part 
it won't work with factors or other non-formal classes.

B)

Since it is sufficient to use anything that inherits from "vector" and 
"factor", I also tried the following one which seems to be cleaner than 
using "ANY" directly.

setClassUnion("myunion", representation("vector", "factor"))	# 
works
setClass("myclass", representation("myunion", x="numeric", 
y="numeric"))

new("myclass", 1:10)		# fails

Now it isn't possible to assign anything as data part at all, as long as 
the union contains any non-formal classes such as "factor". Replacing 
"factor" with a formal class will do, of course.

I wonder if there is some way that does the trick because other 
approaches aren't very straightforward. The obvious solution would be 
a list as .Data part which can store anything but that isn't easy to 
maintain. My goal is to have a formal class whose objects (i.e. .Data 
part) can either be anything derived from "vector" or a factor (ordered). 
I already played around with setIs() for implicit coercion but that doesn't 
do anything as long as one of the classes is an S3 class.

Thanks for your help,

Torsten




More information about the R-help mailing list