[R] Overloading in R

SHRIKANTH SHANKAR shrikanth.shankar at gmail.com
Sun Feb 15 05:29:55 CET 2009


I have been trying to write a new class that reimplements the vector
class. As a test of my overloading I decided to try and and call
t.test on two vectors which were objects of my class rather than the
default class.

The  overloaded length I wrote seems to work correctly. I used
setMethod("length", "myvector", ...)
setMethod("mean", "myvector", ...)
setMethod("var", "myvector", ...)

and created an object

myv <- new("myvector",...)

and when I called t.test(myv, myv)
it first failed in the line

mx <- mean(x)

with the error that "x is not atomic

I finally worked around by doing

"mean.myvector" <- function(x, ...) {

I now get the same error in the next line

vx <- var(x)

I tried doing
"var.myvector" <- function(x,....) as well as
"var.myvector" <- function(x, y=NULL, na.rm=FALSE, use)

all to no luck

from within R I see the following

> showMethods("var")

Function "var":
 <not a generic function>
> var
function (x, y = NULL, na.rm = FALSE, use)
{
..
}
<environment: namespace:stats>

I *think* I understand that this has something to do with the fact
that no generic function is declared for var so my function is not
getting dispatched but with my limited knowledge of R I wasnt able to
get setGeneric to work...

Any suggestions?

Apologies if this is answered somewhere else.

Thanks,
Shrikanth




More information about the R-help mailing list