【问题标题】:How to return predicted values, residuals, R square from lm()?如何从 lm() 返回预测值、残差、R 平方?
【发布时间】:2014-01-03 15:53:23
【问题描述】:

这段代码将返回系数: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 平方、..等?

我需要一些通用的东西来从摘要中提取我需要的东西吗?

【问题讨论】:

标签: r regression linear-regression


【解决方案1】:

这里发生了几件事。

首先,您最好将变量组合到 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

【讨论】:

    【解决方案2】:

    在您的函数中,您只返回系数。尝试返回整个模型:

    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
    

    【讨论】:

    • 然后,不是只返回coef,而是返回你需要的,你甚至可以只返回summary,或者你可以列出你想要的系数和残差和其他统计数据.如果你只有系数,你可以矩阵乘 (%*%) 数据。
    【解决方案3】:

    你需要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
    

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 2012-03-03
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多