簡體   English   中英

如何從 lm() 返回預測值、殘差、R 平方?

[英]How to return predicted values, residuals, R square from lm()?

這段代碼將返回系數 :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)
}

如果我輸入:

   > res[[1]]

我得到:

      (Intercept)          x1          x2 
     -0.44803887  0.06398476 -0.62798646 

我們如何返回預測值、殘差、R 平方等?

我需要一些通用的東西來從摘要中提取我需要的任何東西?

這里有幾件事情正在發生。

首先,最好將變量組合到 data.frame 中:

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

如果您這樣做,使用您的模型對新數據集進行預測會容易得多。

其次,擬合的一些統計數據可以從模型本身訪問,有些可以從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

要獲取系數的統計信息,您需要使用 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

在您的函數中,您只返回系數。 嘗試返回整個模型:

lm.ft=function(y,x1,x2) lm(y~x1+x2) # You don't need the return statement.

現在試試你的代碼,然后運行:

summary(res[[1]])

# Call:
#   lm(formula = y ~ x1 + x2)
# 
# Residuals:
#   Min       1Q   Median       3Q      Max 
# -0.88518 -0.25311  0.03868  0.43110  0.61753 
# 
# Coefficients:
#   Estimate Std. Error t value Pr(>|t|)  
# (Intercept) -0.44804    0.32615  -1.374   0.2119  
# x1           0.06398    0.24048   0.266   0.7979  
# x2          -0.62799    0.26915  -2.333   0.0524 .
# ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Residual standard error: 0.6149 on 7 degrees of freedom
# Multiple R-squared:  0.5173,  Adjusted R-squared:  0.3794 
# F-statistic: 3.751 on 2 and 7 DF,  p-value: 0.07814

你需要predict ——

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)
    return(lm(y~x1+x2))

  res=lm.ft(y,x1,x2)
ypredicted <- predict(res)
residuals <- y - ypredicted

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM