[R] Creating and Using Objects in R
Lorenzo Isella
lorenzo.isella at gmail.com
Thu Jul 9 18:24:46 CEST 2009
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
More information about the R-help
mailing list