Rで求めた線形回帰の結果の整形

Rの関数 lm {stats} を利用して求めた線形回帰の結果を各種関数を利用して整形、出力します。

始めにサンプルとするモデルを作成します。

set.seed(20241114)
library(dplyr)
n <- 30
x1 <- runif(n = n, min = 1, max = 10)
x2 <- runif(n = n, min = 1, max = 10)
b <- 1
X <- as.matrix(cbind(1, x1, x2))
e <- rnorm(n = n, mean = 0, sd = 1)
beta <- c(5, 2, 4) %>% matrix(ncol = 1)
y <- X %*% beta + e
(beta_hat <- solve(t(X) %*% X) %*% t(X) %*% y)
       [,1]
   4.845184
x1 2.096882
x2 3.922783
(lm_model <- lm(y ~ x1 + x2))

Call:
lm(formula = y ~ x1 + x2)

Coefficients:
(Intercept)           x1           x2  
      4.845        2.097        3.923  

以下の関数を利用して、求めた結果を整形、出力します。

  1. summary {base}
  2. summ {jtools}
  3. stargazer {stargazer}
  4. htmlreg {texreg}
  5. tidy {broom}
  6. modelsummary {modelsummary}

summary {base}
lm_model %>% summary()

Call:
lm(formula = y ~ x1 + x2)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.2012 -0.5021  0.1015  0.4110  1.6739 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.84518    0.46217   10.48 5.11e-11 ***
x1           2.09688    0.05706   36.75  < 2e-16 ***
x2           3.92278    0.06509   60.27  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7865 on 27 degrees of freedom
Multiple R-squared:  0.9957,    Adjusted R-squared:  0.9953 
F-statistic:  3092 on 2 and 27 DF,  p-value: < 2.2e-16

summ {jtools}
jtools::summ(lm_model)
Observations30
Dependent variabley
TypeOLS linear regression
F(2,27)3091.99
1.00
Adj. R²1.00
Est.S.E.t val.p
(Intercept)4.850.4610.480.00
x12.100.0636.750.00
x23.920.0760.270.00
Standard errors: OLS

stargazer {stargazer}
stargazer::stargazer(lm_model, type = "html")
Dependent variable:
y
x1 2.097***
(0.057)
x2 3.923***
(0.065)
Constant 4.845***
(0.462)
Observations 30
R2 0.996
Adjusted R2 0.995
Residual Std. Error 0.787 (df = 27)
F Statistic 3,091.986*** (df = 2; 27)
Note: p<0.1; p<0.05; p<0.01

htmlreg {texreg}
texreg::htmlreg(lm_model)
Statistical models
  Model 1
(Intercept) 4.85***
  (0.46)
x1 2.10***
  (0.06)
x2 3.92***
  (0.07)
R2 1.00
Adj. R2 1.00
Num. obs. 30
***p < 0.001; **p < 0.01; *p < 0.05

tidy {broom}
broom::tidy(lm_model)
# A tibble: 3 × 5
  term        estimate std.error statistic  p.value
  <chr>          <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept)     4.85    0.462       10.5 5.11e-11
2 x1              2.10    0.0571      36.7 1.36e-24
3 x2              3.92    0.0651      60.3 2.52e-30

modelsummary {modelsummary}
modelsummary::modelsummary(lm_model)
(1)
(Intercept)4.845
(0.462)
x12.097
(0.057)
x23.923
(0.065)
Num.Obs.30
R20.996
R2 Adj.0.995
AIC75.6
BIC81.2
Log.Lik.-33.784
F3091.986
RMSE0.75

以上です。