[R] Making an S3 object act like a data.frame

Gabor Grothendieck ggrothendieck at gmail.com
Wed Mar 8 00:18:53 CET 2006


On 3/7/06, hadley wickham <h.wickham at gmail.com> wrote:
> > Just to get something reproducible lets assume the
> > objects of class "myobj" each consists of a one-element
> > list that contains a data frame.  Then try this:
>
> Thanks for that - it makes sense.  Every time I try to use inheritance
> in R, I always seem to end up using a different method.
>
> Hadley
>

I tend to have to use trial and error myself.  Here is another
possibility.

myobj <- function(...)
	structure(list(value = data.frame(...)), class = "myobj")

"$.myobj" <- function(obj, name) obj[[name]]

"[[.myobj" <- function(obj, ...) {
	obj <- .subset2(obj, 1)
	.Class <- "data.frame"
	NextMethod("[[", obj)
}

"[.myobj" <- function(obj, ...) {
	obj <- .subset2(obj, 1)
	.Class <- "data.frame"
	NextMethod("[", obj)
}
# test
z <- myobj(x = 1:3, y = 4:6)
class(z)
z[[1]]
z[1,]
z$y
z[["x"]]




More information about the R-help mailing list