在R中提取回归P值

23

我将在查询文件中对不同列执行多元回归分析。我的任务是从R中的回归函数lm中提取特定结果。

目前我已经完成了以下工作:

> reg <- lm(query$y1 ~ query$x1 + query$x2)
> summary(reg)

Call:
lm(formula = query$y1 ~ query$x1 + query$x2)

Residuals:
    1     2     3     4 
  7.68 -4.48 -7.04  3.84 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  1287.26     685.75   1.877    0.312
query$x1      -29.30      20.92  -1.400    0.395
query$x2     -116.90      45.79  -2.553    0.238

Residual standard error: 11.97 on 1 degrees of freedom
Multiple R-squared:  0.9233,    Adjusted R-squared:  0.7699 
F-statistic: 6.019 on 2 and 1 DF,  p-value: 0.277

为了提取系数、R平方和F统计量,我使用以下方法:
reg$coefficients
summary(reg)$r.squared
summary(reg)$fstatistic

我希望还能提取0.277的p值。
有没有可以做到这一点的代码?
谢谢。

5个回答

17

我建议在可能需要从模型拟合输出中创建数据框的情况下,使用“broom”软件包作为良好的实践方法。

以下是一个简单的示例:

library(broom)

dt = data.frame(mtcars) # example dataset

model = lm(mpg ~ disp + wt, data = dt) # fit a model

summary(model) # usual summary of a model fit

tidy(model) # get coefficient table as a data frame

glance(model) # get rest of stats as a data frame

glance(model)$p.value # get p value

12
我发现提取p值最简单的两种方法是:
summary(Model)$coefficients[,"Pr(>|t|)"]

summary(Model)$coefficients[,4]

只需将Model替换为您的模型名称即可。


好的解决方案。此外,在末尾添加一个额外的括号只返回值(不包括名称): summary(Model)$coefficients[,"Pr(>|t|)"][[2]] - hekimgil
这应该是首选解决方案。 - ColorStatistics

7
您可以使用anova(reg)$'Pr(>F)'来实现。

这是最好的。 - ABCD

3

你也可以使用:

pf(summary(reg)$fstatistic[1],
summary(reg)$fstatistic[2],
summary(reg)$fstatistic[3],
lower.tail=FALSE)

0

这非常有帮助!我能够补充的唯一细节是,如果想要向现有数据集添加包括系数值的列,也可以像这样访问系数值:

allvars$predicted = allvars$x*summary(fit)$coefficients[2,1] + summary(fit)$coefficients[1,1]

而且,显然是通过差异计算残差:

allvars$residuals = allvars$y - (allvars$x*summary(fit)$coefficients[2,1]

再次感谢 ADR


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接