Re: [R] extract data from lm object and then use again?

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Fri 22 Sep 2006 - 15:21:40 GMT

On Fri, 2006-09-22 at 10:45 -0400, Mike Wolfgang wrote:
> Hi list,
>
> I want to write a general function so that it would take an lm object,
> extract its data element, then use the data at another R function (eg, glm).
> I searched R-help list, and found this would do the trick of the first part:
> a.lm$call$data
> this would return a name object but could not be recognized as a
> data.frameby glm. I also tried
> call(as.character(a.lm$call$data))
> or
> eval(call(as.character(a.lm$call$data)))
> neither works.
>
> By eval(call(...)), it acts as evaluating of a function, but what I want is
> just a data frame object which could be inserted into glm function. Anyone
> could help? Thanks,
>
> Mike

If the 'data' argument in lm() is used, then this approach could work:

> Iris2 <- eval(lm(Sepal.Length ~ Species, data = iris)$call$data)

> str(Iris2)

`data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1
1 1 1 1 1 ...

However, note that you do not get the actual data used within the lm() function (the model frame) but the entire source data frame.

What you likely want instead is the model frame containing the columns actually used in the model formula:

> Iris3 <- lm(Sepal.Length ~ Species, data = iris)$model

> str(Iris3)

`data.frame': 150 obs. of 2 variables:  $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...  $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

HTH, Marc Schwartz



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat Sep 23 01:24:07 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 22 Sep 2006 - 16:30:47 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.