[R] Class & Method, S3 / S4

Martin Morgan mtmorgan at fhcrc.org
Wed Mar 1 19:16:05 CET 2006


The object paradigm in R is different; I like to think of methods as
orthogonal to classes, instead of nested within them.

Probably what you want to try is

# a generic function, to operate on different classes
setGeneric("test", function( obj ) standardGeneric( "test" ))

# a class, containing data
setClass("connect", representation( value = "numeric" ))

# a specific method, operating on "connect" objects
setMethod("test", signature=c("connect"),
  function( obj ) { obj at value / 2 })

# a new object of class "connect" with value slot assigned 44
testObj <- new("connect", value=44 )
# application of the generic function to an object of class "connect",
# dispatched to the method operating on objects of class "connect"
test( testObj )  

This kind of structuure makes some types of operations particularly
natural in R -- dispatch on multiple arguments, for instance.

Hope that helps,

Martin


mailto-nik at bluemail.ch writes:

> Hi
>
> I'm trying to create a class. However, I've some problems...
>
> I am used to program php. There I can create a new object and call a specific
> function of this object. In R, I hoped to create a class similar and then
> call the function like:
>
> Creating the Class:
> <CODE>-----------------------------------
> setClass("connect",
> 		representation(test="function"))
> )
>
> setMethod("test", "connect", 
>     function(value){ 
>         value /2
> 	}
> )
> </CODE>-----------------------------------
>
>
> testObj = new ("connect")
> testObj at test(44)
>
> That should return 22. However, unfortunately it does not work. How can I
> solve this problem. I read several instructions, but how does R work???.
> Does anybody have a very simple example like above.
>
> I highly appreciate any help.
> Thanks a lot.
> Nik
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list