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?
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With