[R] S4 classes, some help with the basics

Martin Morgan mtmorgan at fhcrc.org
Tue Aug 9 04:14:47 CEST 2011


On 08/08/2011 05:04 PM, Mike Williamson wrote:
> Hi All,
>
>      I have tried to find an answer within documentation, but I cannot:
>
> o How can call a class "slot" without knowing the name a priori?
>
>      E.g., let's say I use the "pcaMethods" library to create a "pcaRes"
> object.  How can I call parts of that object without using the specific
> names of the object in the call?
>
> example code:
>
> library(pcaMethods)
> myMatrix<- matrix(runif(1e4), ncol=100)  ## silly, but sufficient for
> example
> myPCA<- pca(myMatrix)  ## creates a "pcaRes" S4 class
>
> for (i in slotNames(myPCA) ) {
>       summary(myPCA at i)  ### I know this doesn't work, but this is the
> question... what grammar could I use?
> }

usually one doesn't want to directly access S4 slots, but instead use 
accessors defined by the author, e.g., completeObs(myPCA). The idea is 
that the implementation of the class might deviate from the interface. 
Methods might be documented on the class help page

   class(myPCA)
   class?pcaRes

or discoverable

   showMethods(class="pcaRes", where=getNamespace("pcaMethods"))

Martin

> ################
>
> I would like to be able to print out the summary for each of the components
> of the class "pcaRes" without knowing a priori the names of those
> components.  I could, for example in the above case, type in
> summary(myPCA at completeObs) to get a summary of the input matrix.  But I HAVE
> TO TYPE "@completeObs".  In the non-S4 world, I could type myPCA[[i]] for
> lists, where "i" could be looping through either the list names, or the list
> indices.  Similarly, I could type myPCA[i] for arrays, where "i" again can
> be either a numeric index or the name.
>
> Without this ability to identify portions within an array / loop context, it
> becomes exceedingly difficult to work in "S4 land".  How is this sort of
> thing done?
>
>                                  Thank you!
>                                           Mike
>
>
>
> ---
> XKCD<http://www.xkcd.com>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.


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

Location: M1-B861
Telephone: 206 667-2793



More information about the R-help mailing list