« Return to Thread: Creating and Using Objects in R

Creating and Using Objects in R

by Lorenzo Isella :: Rate this Message:

Reply to Author | View in Thread

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@... 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.

 « Return to Thread: Creating and Using Objects in R