[R] Making an S3 object act like a data.frame
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Mar 9 19:29:04 CET 2006
I think the problem is that your ggobiDataset objects are also
data.frame objects. They must NOT be. For example,
note how the following example fails once we add "data.frame"
to the class vector of x: The reason is that ordinary inheritance
is not used by model.frame; rather, it uses is.data.frame
to make the determination so by having data.frame in
your class vector it does not try to convert it.
> # constructor
> myobj <- function(...)
+ structure(list(value = data.frame(...)), class = "myobj")
>
> "$.myobj" <- function(obj, x) .subset2(obj, 1)[[x]]
> "[[.myobj" <- function(obj, ...) .subset2(obj, 1)[[...]]
> "[.myobj" <- function(obj, ...) .subset2(obj, 1)[...]
> as.data.frame.myobj <- function(x) .subset2(x, 1)
>
> # test
> x <- myobj(x = 1:3, y = 4:6)
> class(x)
[1] "myobj"
> lm(y ~ x, x)
Call:
lm(formula = y ~ x, data = x)
Coefficients:
(Intercept) x
3 1
>
> # now change class of x
> class(x) <- c("myobj", "data.frame")
> lm(y ~ x, x)
Error in eval(expr, envir, enclos) : object "y" not found
>
On 3/9/06, hadley wickham <h.wickham at gmail.com> wrote:
> > Can you create a small self contained reproducible example
> > that does not work? The reproducible example I provided earlier on
> > this thread worked fine.
>
> I wish I could, and I'm very grateful for the help, but because the
> data is an external pointer it's not easy to make a self-contained
> example.
>
> > str.default(x)
> Classes ggobiDataset and `data.frame': 32 obs. of 1 variable:
> Classes 'ggobiDataset', 'data.frame' <externalptr>
> - attr(*, "ggobi")=Class 'ggobi' <externalptr>
> > getAnywhere("str.default")$objs[[1]](x)
> Classes 'ggobiDataset', 'data.frame' <externalptr>
> - attr(*, "ggobi")=Class 'ggobi' <externalptr>
>
> > One idea is to check what the class is of the output of
> > your .GGobiCall. If it were of class ggobiDataset then
> > it would in turn be calling as.data.frame.ggobiDataset
> > again. I mention this since the problem in
> > your reproducible example was precisely of that
> > sort.
>
> > class(x)
> [1] "ggobiDataset" "data.frame"
> > class(as.data.frame(x))
> [1] "data.frame"
>
> So I don't think that's the problem.
>
> Thanks again for your help.
>
> Hadley
>
More information about the R-help
mailing list