[R] S4 class questions

Martin Morgan mtmorgan at fhcrc.org
Thu Jul 10 18:30:44 CEST 2008


"Li, Xuejun" <XueLi at coh.org> writes:

>  
>
> Hi, I'd like to create a S4 class contains only one type of data.
> However, the number of slots varies.
>
> For example, I want to create a class "a", each slots in "a" contains
> numeric value only.  
>
>> setClass("a", contains = "numeric")
>
> If I want to create an object "a" with only one slot containing c(3,4),
> I will write
>
>> new("a", c(3,4))
>
> What if I want to create another object "a" with three slots with c(3,4)
> in the 1st slot, c(1,2) in the second, and c(0, 5) in the third?

Your class definition says that 'a' has just one slot, so you can't
have three slots. Maybe you want to create another class, or a little
class hierarchy,

setClass("a") # 'VIRTUAL'

setClass("a1, contains="a",
         representation=represention(
           a1="numeric"
         ))

setClass("a2, contains="a",
         representation=represention(
           a1="numeric",
           a2="numeric"
         ))

or maybe you want to create a class that that can contain a list of
numeric vectors, e.g.,

setClass("avector", contains="list",
         validity=function(object) {
             ok <- sapply(slot(object, ".Data"), is, "numeric")
             if (!all(ok)) "values must be numeric"
             else TRUE
         })

and then

> new("avector")
An object of class "avector"
list()
> new("avector", list(1:10, 5:1))
An object of class "avector"
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1]  5  4  3  2  1

> new("avector", list(1:10,letters))
Error in validObject(.Object) : 
  invalid class "avector" object: values must be numeric

Martin

>
>  
>
>  
>
>  
>
>  
>
> Arthur Xuejun Li
>
> Division of Information Science
>
> 1500 East Duarte Road
>
> Duarte, CA 91010 - 3000
>
> Ph:   (626) 256-4673 ext. 65121
>
> Fax: (626) 471-7106
>
>  
>
>
>
> ---------------------------------------------------------------------
>
> SECURITY/CONFIDENTIALITY WARNING:  \ This message an...{{dropped:23}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Martin Morgan
Computational Biology / Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N.
PO Box 19024 Seattle, WA 98109

Location: Arnold Building M2 B169
Phone: (206) 667-2793



More information about the R-help mailing list