[R] Creating and Using Objects in R

Gabor Grothendieck ggrothendieck at gmail.com
Thu Jul 9 18:45:41 CEST 2009


Here it is done without S3.  Note that UseMethod
is basically just an alternative to an if statement.
Perhaps this makes it more understandable.

x1 <- list(x = 1, y = 2)
class(x1) <- "xypoint"
x2 <- list(r = 1, theta = pi/2)
class(x2) <- "rthetapoint"

XPOS <- function(x) {
	if (inherits(x, "xypoint")) xpos.xypoint(x)
	else if (inherits(x, "rthetapoint")) xpos.rthetapoint(x)
	else stop("Cannot find appropriate class")
}

XPOS(x1) # without S3
xpos(x1) # using S3

XPOS(x2) # without S3
xpos(x2) # using S3


On Thu, Jul 9, 2009 at 12:24 PM, Lorenzo Isella<lorenzo.isella at gmail.com> wrote:
> Dear All,
> I am not very into object-oriented programming, but I would like to learn
> the ropes for some R applications.
> Quoting from the online R language definition (paragraph 5.1)
>
>> Consider the following simple example. A point in two-dimensional
>> Euclidean space can be specified by its Cartesian (x-y) or polar (r-theta)
>> coordinates. Hence, to store information about the location of the point, we
>> could define two classes, |"xypoint"| and |"rthetapoint"|. All the `xypoint'
>> data structures are lists with an x-component and a y-component. All
>> `rthetapoint' objects are lists with an r-component and a theta-component.
>>
>> Now, suppose we want to get the x-position from either type of object.
>> This can easily be achieved through generic functions. We define the generic
>> function |xpos| as follows.
>>
>>     xpos <- function(x, ...)
>>         UseMethod("xpos")
>>
>> Now we can define methods:
>>
>>     xpos.xypoint <- function(x) x$x
>>     xpos.rthetapoint <- function(x) x$r * cos(x$theta)
>>
>> The user simply calls the function |xpos| with either representation as
>> the argument. The internal dispatching method finds the class of the object
>> and calls the appropriate methods.
>>
> I am a bit confused: when calling e.g. xpos.rthetapoint, I understand that x
> contains the polar representation of a point, so x=(r,theta), but  how do I
> exactly  write it to pass it to xpos.rthetapoint? I have made several
> attempts, but so far none of them works, so I may have misunderstood
> something.
> Many thanks
>
> Lorenzo
>
> ______________________________________________
> 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.
>




More information about the R-help mailing list