[R] using setMethod or setGeneric to change S4 accessor symbol from @ to $

Martin Morgan mtmorgan at fhcrc.org
Mon Feb 8 20:44:11 CET 2010


On 02/07/2010 08:31 PM, Markus Weisner wrote:
> I created some S4 objects that are essentially data frame objects.  The S4
> object definitions were necessary to verify data integrity and force a
> standardized data format.  I am, however, finding myself redefining all the
> typical generic functions so that I can still manipulate my S4 objects as if
> they were data frames ... I have used setMethod to set methods for "subset",
> "head", and "tail".  I would like to use setMethod or setGeneric to enable
> me to use object$slotname to access object at slotname for my S4 objects.  Any
> advice is appreciated.  Thanks.

Hi Markus --

> setClass("A", representation(a="numeric"))
[1] "A"
> new("A")$a
Error in new("A")$a : $ operator not defined for this S4 class
> getGeneric("$")
standardGeneric for "$" defined from package "base"

function (x, name)
standardGeneric("$", .Primitive("$"))
<environment: 0xa62028>
Methods may be defined for arguments: x
Use  showMethods("$")  for currently available ones.
> setMethod("$", "A", function(x, name) slot(x, name))
[1] "$"
> new("A", a=1:10)$a
 [1]  1  2  3  4  5  6  7  8  9 10
> new("A", a=1:10)$b
Error in slot(x, name) : no slot of name "b" for this object of class "A"

does that help?

Martin

> --Markus
> 
> 	[[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.


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

Location: Arnold Building M1 B861
Phone: (206) 667-2793



More information about the R-help mailing list