Re: [R] Puzzled in utilising summary.lm() to obtain Var(x)

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Wed 15 Jun 2005 - 13:52:56 EST

On 6/14/05, Ajay Narottam Shah <ajayshah@mayin.org> wrote:
> > > I have a program which is doing a few thousand runs of lm(). Suppose
> > > it is a simple model
> > > y = a + bx1 + cx2 + e
> > >
> > > I have the R object "d" where
> > > d <- summary(lm(y ~ x1 + x2))
> > >
> > > I would like to obtain Var(x2) out of "d". How might I do it?
> > >
> > > I can, of course, always do sd(x2). But it would be much more
> > > convenient if I could snoop around the contents of summary.lm and
> > > extract Var() out of it. I couldn't readily see how. Would you know
> > > what would click?
> >
> > Is the question how to get the variance of a column of the
> > model matrix for a model that is the sum of terms given only
> > summary output and the column name but not the name of the
> > data frame? If that is it then try this:
> >
> > d <- summary(lm(Sepal.Length ~ Sepal.Width, iris)) # test data
> > var(model.matrix(eval(d$call))[,"Sepal.Width"])
>
> Yes, this is indeed exactly what I was looking for :-) Thanks,
>
> The eval() pays the full cost of running d$call?

Yes. It reruns it. If we can assume that the second arg to lm is data= then we could do this which simply grabs the indicated column from the data frame:

f <- function(d, name) eval(substitute(with(eval(d$call[[3]]), name))) f(d, Sepal.Width) # same as iris$Sepal.Width

# or

f <- function(d, charname) eval(d$call[[3]])[[charname]] f(d, "Sepal.Width")



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 Received on Wed Jun 15 13:56:11 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:39 EST