r - 使用 lm : Different summary output in a function 在 R 中进行线性回归

标签 r linear-regression lm

关于使用 lm 函数在 R 中进行线性回归的简短问题。我注意到将 summary 命令用作函数的一部分时输出不同。

当我输入时:

model1 <- lm (PostVal_Ave ~ Int)
summary(model1)

控制台返回如下内容:

Call:
lm(formula = PostVal_Ave ~ Int)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.9871 -0.8897  0.4853  1.0129  1.5129 

Coefficients:
        Estimate Std. Error t value Pr(>|t|)
(Intercept)   5.4871     0.1426  38.491   <2e-16
Int           0.2776     0.1988   1.396    0.164

(Intercept) ***
Int            
---
Signif. codes:  
0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.322 on 175 degrees of freedom
(35 observations deleted due to missingness)
Multiple R-squared:  0.01102,   Adjusted R-squared:  0.005366 
F-statistic: 1.949 on 1 and 175 DF,  p-value: 0.1644

但是,在编写函数以便能够为多个模型生成输出并能够为多个因变量生成结果时,我输入:

allModels <- function(x){
    model2 <- lm (x ~ Int)
    model2.1 <- lm (x ~ Int + cPreEff)
    model2.2 <- lm (x ~ Int + cPreEff + Gender + Grade)
    return(c(summary(model1), summary(model1.1), summary(model1.2)))}

与模型 1 的输出相比,我得到了相同的输出,但是这三个模型(model2、model2.1 和 model2.2)有很多额外的输出。具体来说,输出包含三个模型中每个模型的每个案例的残差以及有关每个具有缺失数据的案例的信息。建议将不胜感激。谢谢。

最佳答案

请注意,lm() 返回一个“lm”类的对象,而该对象上的 summary() 会生成一个“summary.lm”对象。有自定义 print.lm()print.summary.lm() 对象。因此,打印到控制台的内容可能与对象本身的内容不同。

当您手动连接 (c()) 两个 summary.lm 对象时,您创建了一个聚合列表并丢失了正确的类。您可能想返回一个对象列表

return(list(summary(model1), summary(model1.1), summary(model1.2)))

关于r - 使用 lm : Different summary output in a function 在 R 中进行线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27474961/

相关文章:

使用 lm() 和 predict() 进行滚动回归和预测

python - 如何为向量输入和观测值建立线性最小二乘回归模型

r - 如何保存 Twitter 身份验证凭据以在 Shiny 的应用程序中重复使用?

r - Highcharts 中的 dash_styles

r - 在使用过滤器时使用 get() 按列分组在某些情况下不起作用

Python线性回归,残差的最佳拟合线

opencv - opencv中有求解xA=b的函数吗?

r - 如何使用 purrr 迭代 lm reg 中协变量和结果的每个组合

r - lm.fit(x, y, offset = offset, single.ok = single.ok, ...) : NA/NaN/Inf in 'y' , 中的错误尝试了所有可能的方法

r - 在 ggplot2 中绘制岛屿