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

Gabor Grothendieck ggrothendieck at gmail.com
Wed Mar 8 02:49:55 CET 2006

The problem is that x[[1]] in the definition of as.data.frame.myobj
invokes [[.myobj whereas we want to extract the first element of the
list in the internal representation of x -- which is not the same.

Try this instead:

> as.data.frame.myobj <- function(x) .subset2(x, 1)
> lm(y ~ x, z)

lm(formula = y ~ x, data = z)

(Intercept)            x
          3            1

On 3/7/06, hadley wickham <h.wickham at gmail.com> wrote:
> > I tend to have to use trial and error myself.  Here is another
> > possibility.
> That's got the subsetting solved, so here's the next challenge
> > lm(x ~ y, z)
> Error in as.data.frame.default(data) : cannot coerce class "myobj"
> into a data.frame
> > as.data.frame.myobj <- function(x) x[[1]]
> > lm(x ~ y, z)
> Error in eval(expr, envir, enclos) : numeric 'envir' arg not of length one
> I'm guessing this is pretty much impossible to get around, because
> there is no way to tell eval how to deal with myobj type objects, and
> lm only dispatches based on the type of the first argument.
> Hadley

More information about the R-help mailing list