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

R, RStudio, Quarto and STEM(Science, Technology, Engineering and Mathematics)

Note

本ページは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  
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)
Observations 30
Dependent variable y
Type OLS linear regression
F(2,27) 3091.99
1.00
Adj. R² 1.00
Est. S.E. t val. p
(Intercept) 4.85 0.46 10.48 0.00
x1 2.10 0.06 36.75 0.00
x2 3.92 0.07 60.27 0.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)
x1 2.097
(0.057)
x2 3.923
(0.065)
Num.Obs. 30
R2 0.996
R2 Adj. 0.995
AIC 75.6
BIC 81.2
Log.Lik. -33.784
F 3091.986
RMSE 0.75

最終更新

Sys.time()
[1] "2024-11-27 14:12:56 JST"

R、Quarto、Package

R.Version()$version.string
[1] "R version 4.4.1 Patched (2024-06-15 r86781 ucrt)"
quarto::quarto_version()
[1] '1.5.57'
packageVersion(pkg = 'tidyverse')
[1] '2.0.0'

著者