[R] extracting information from an object
David Howell
David.Howell at uvm.edu
Tue Aug 10 20:27:20 CEST 2010
I was working on a project involving a linear model, and wanted to
extract the standard error of a predictor. I am able to do so, but not
in the way I would expect.
I would have expected that if a created a model such as Model1 <-
lm(y~x,z,d), the object Model1 would contain that information even
though it does not print it out when I simply type Model1. I would also
have (wrongly) suspected that if I type summary(Model1) R would simply
look at the object Model1 and find whatever it needs. But it doesn't
work that way. If I want that standard error I have to first create a
summary of Model1 and then extract the standard error from the summary
with something like summary(Model1)$coefficients or, more specifically,
summary(Model)$coefficients[2,2]. [I know that I can cram all of that
into one line if I want to.] But doesn't that mean that when I ask for a
summary R has to recreate the linear model all over again before pulling
out the standard error. (Venables and Ripley, p. 77) suggest that this
could happen if the method is not written correctly, but how is it not
happening anyway?) And if so, if Model1 doesn't contain the raw data,
how does summary produce an answer even if I delete one of the variables
before calling it?
As you can see, I have figured out how to get what I want, but I don't
understand the process of building objects, which is the important thing
to understand. Perhaps I don't understand "methods" well enough.
Below is sample code:
#Sample for linear model
x <- c(3,7,9,15,18)
y <- c(5,4,8,6,9)
reg <- lm(y~x)
reg
#Produces only the regression coefficients and using str(reg) indicates
that
# that is all that it has.
regsummary <- summary(reg)
#Produces what I need and str(regsummary) shows that st. errors are part
of the object.
regsummary$coefficients[1:2, 1:4]
rm(y)
out <- summary(reg)
# works just fine although y is no longer available and reg doesn't look
like it
# could supply it.
Thanks,
Dave Howell
More information about the R-help
mailing list