从R中的lm函数中提取t统计量p值

11
我使用lm函数在R中运行了回归模型。结果的ANOVA表格给出了每个系数的F值(这对我来说并没有太多意义)。我想知道的是每个系数的t统计量及其相应的p值。我该如何获取这些信息?它是否由该函数存储,还是需要进行额外的计算?
以下是代码和输出:
library(lubridate)
library(RCurl)
library(plyr)

[in] fit <- lm(btc_close ~ vix_close + gold_close + eth_close, data = all_dat)

# Other useful functions 
coefficients(fit) # model coefficients
confint(fit, level=0.95) # CIs for model parameters 
anova(fit) # anova table 

[out]
Analysis of Variance Table

Response: btc_close
           Df   Sum Sq  Mean Sq  F value Pr(>F)    
vix_close   1 20911897 20911897 280.1788 <2e-16 ***
gold_close  1    91902    91902   1.2313 0.2698    
eth_close   1 42716393 42716393 572.3168 <2e-16 ***
Residuals  99  7389130    74638                    
---
Signif. codes:  0***0.001**0.01*0.05 ‘.’ 0.1 ‘ ’ 1

如果我的统计学知识没错的话,这些F值是没有意义的。理论上,我应该得到一个模型的F值和每个系数的T值。

2
使用 broom 包和 tidy(fit) - Benjamin
1
F 是 t^2(当分子 df = 1 时)。p 值不会改变。 - Jeremy Miles
2
使用 summary(fit) 时,您会得到 t 值。 - Axeman
5个回答

16

这里有一个带注释的示例,展示了如何提取仅 t 值。

# Some dummy data
n <- 1e3L
df <- data.frame(x = rnorm(n), z = rnorm(n))
df$y <- with(df, 0.01 * x^2 + z/3)

# Run regression
lr1 <- lm(y ~ x + z, data = df)

# R has special summary method for class "lm"
summary(lr1)
# Call:
# lm(formula = y ~ x + z, data = df)

# Residuals:
#       Min        1Q    Median        3Q       Max 
# -0.010810 -0.009025 -0.005259  0.003617  0.096771 

# Coefficients:
#              Estimate Std. Error t value Pr(>|t|)    
# (Intercept) 0.0100122  0.0004313  23.216   <2e-16 ***
# x           0.0008105  0.0004305   1.883     0.06 .  
# z           0.3336034  0.0004244 786.036   <2e-16 ***
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

# Residual standard error: 0.01363 on 997 degrees of freedom
# Multiple R-squared:  0.9984,  Adjusted R-squared:  0.9984 
# F-statistic: 3.09e+05 on 2 and 997 DF,  p-value: < 2.2e-16

# Now, if you only want the t-values
summary(lr1)[["coefficients"]][, "t value"]
# Or (better practice as explained in comments by Axeman)
coef(summary(lr1))[, "t value"]
# (Intercept)           x           z 
#   23.216317    1.882841  786.035718 

anova函数的更常见用法可能是像anova(lm(y ~ x + z, data = df), lm(y ~ z, data = df ))这样的,测试模型在没有x和有x的情况下是否不同。请注意,正如Jeremy指出的那样,F值是t值的平方。 - s_baldur
5
或者 coef(summary(lr1))[, "t value"] - Axeman
1
我猜使用coef函数的好处是它总是有效的,即使内部发生变化,并且它可以用于许多其他模型对象。 - Axeman

5
你可以尝试这个方法:
   summary(fit)

4

使用summary(fit)$coefficients[,4]可以获取p值;

使用summary(fit)$coefficients[,3]可以获取t值。


3

正如 Benjamin 已经回答的那样,我建议使用 broom::tidy() 将模型对象转换为整洁的数据框。统计列将包含相关的检验统计量,并可轻松使用 ggplot2 进行绘图。


0

你可以使用这个

summary(fit)$coefficients[,3]

提取仅t值


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