Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

regression - How to return predicted values, residuals, R square from lm()?

this piece of code will return coefficients :intercept , slop1 , slop2

set.seed(1)
n=10

y=rnorm(n)
x1=rnorm(n)
x2=rnorm(n)

lm.ft=function(y,x1,x2)
  return(lm(y~x1+x2)$coef)

res=list();
for(i in 1:n){
  x1.bar=x1-x1[i]
  x2.bar=x2-x2[i]
  res[[i]]=lm.ft(y,x1.bar,x2.bar)
}

If I type:

   > res[[1]]

I get:

      (Intercept)          x1          x2 
     -0.44803887  0.06398476 -0.62798646 

How can we return predicted values,residuals,R square, ..etc?

I need something general to extract whatever I need from the summary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are a couple of things going on here.

First, you are better off combining your variables into a data.frame:

df  <- data.frame(y=rnorm(10), x1=rnorm(10), x2 = rnorm(10))
fit <- lm(y~x1+x2, data=df)

If you do this, using you model for prediction with a new dataset will be much easier.

Second, some of the statistics of the fit are accessible from the model itself, and some are accessible from summary(fit).

coef  <- coefficients(fit)       # coefficients
resid <- residuals(fit)          # residuals
pred  <- predict(fit)            # fitted values
rsq   <- summary(fit)$r.squared  # R-sq for the fit
se    <- summary(fit)$sigma      # se of the fit

To get the statistics of the coefficients, you need to use summary:

stat.coef  <- summary(fit)$coefficients
coef    <- stat.coef[,1]    # 1st column: coefficients (same as above)
se.coef <- stat.coef[,2]    # 2nd column: se for each coef
t.coef  <- stat.coef[,3]    # 3rd column: t-value for each coef
p.coef  <- stat.coef[,4]    # 4th column: p-value for each coefficient

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...