통계 결과 테이블 (gt, kableExtra)
분석 결과를 복사하여 Word에 붙여넣고 손으로 표를 만들던 시절이 있었습니다. 코드로 결과 테이블을 자동 생성하면 실수가 없고, 데이터가 바뀌어도 테이블이 자동으로 업데이트됩니다.
broom으로 결과를 데이터프레임으로 변환하기
broom 패키지는 통계 모형 결과를 깔끔한 데이터프레임(tibble)으로 변환합니다. 테이블 생성의 첫 번째 단계입니다.
install.packages("broom")
library(broom)
library(dplyr)
# 회귀 모형
model <- lm(mpg ~ wt + hp + cyl, data = mtcars)
# tidy() — 계수 테이블
tidy(model)
# A tibble: 4 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 38.8 1.79 21.7 1.62e-19
2 wt -3.17 0.741 -4.28 2.01e- 4
3 hp -0.0180 0.0119 -1.52 1.40e- 1
4 cyl -0.942 0.551 -1.71 9.82e- 2
# glance() — 모형 요약 통계
glance(model)
# A tibble: 1 × 12
r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.843 0.826 2.51 50.2 2.18e-11 3 -74.0 158. 165.
# 테이블용으로 포매팅
coef_table <- tidy(model, conf.int = TRUE) |>
mutate(
term = c("(Intercept)", "Weight", "Horsepower", "Cylinders"),
estimate = round(estimate, 3),
std.error = round(std.error, 3),
statistic = round(statistic, 2),
p.value = ifelse(p.value < 0.001, "< .001", round(p.value, 3)),
conf.low = round(conf.low, 3),
conf.high = round(conf.high, 3)
) |>
select(term, estimate, std.error, statistic, p.value, conf.low, conf.high)
gt 패키지로 APA 스타일 테이블 만들기
gt는 ggplot2처럼 레이어를 쌓아 테이블을 만드는 패키지입니다. HTML, PDF, Word 출력을 모두 지원합니다.
install.packages("gt")
library(gt)
coef_table |>
gt() |>
# 헤더
tab_header(
title = "Table 1",
subtitle = "Multiple Regression Analysis Predicting Fuel Efficiency"
) |>
# 컬럼 레이블
cols_label(
term = "Variable",
estimate = "B",
std.error = "SE",
statistic = "t",
p.value = "p",
conf.low = "95% CI LL",
conf.high = "95% CI UL"
) |>
# 정렬: 숫자 열은 가운데
cols_align(align = "center",
columns = c(estimate, std.error, statistic, p.value,
conf.low, conf.high)) |>
cols_align(align = "left", columns = term) |>
# 유의한 행 강조
tab_style(
style = cell_text(bold = TRUE),
locations = cells_body(rows = p.value == "< .001")
) |>
# 각주
tab_footnote(
footnote = "B = unstandardized coefficient; SE = standard error.",
locations = cells_column_labels(columns = estimate)
) |>
# APA 스타일에 가까운 테마
tab_options(
table.border.top.color = "black",
table.border.bottom.color = "black",
column_labels.border.bottom.color = "black",
column_labels.font.weight = "bold",
table.font.size = 11
)
# 파일로 저장
table_obj <- coef_table |> gt() # 위의 gt 체인 적용 후
# HTML로 저장
gtsave(table_obj, "table1_regression.html")
# Word(.docx)로 저장
gtsave(table_obj, "table1_regression.docx")
kableExtra로 PDF 테이블 만들기
R Markdown → PDF 출력 시 kableExtra가 LaTeX과 잘 호환됩니다.
install.packages("kableExtra")
library(kableExtra)
kbl(coef_table,
booktabs = TRUE, # LaTeX booktabs 스타일
longtable = FALSE,
col.names = c("Variable", "B", "SE", "t", "p",
"95% CI LL", "95% CI UL"),
caption = "Multiple Regression Analysis Predicting Fuel Efficiency",
align = "lcccccc") |>
kable_styling(
latex_options = c("striped", "hold_position"),
font_size = 10
) |>
# 굵게 처리
row_spec(which(coef_table$p.value == "< .001"),
bold = TRUE) |>
# 각주
footnote(general = "B = unstandardized coefficient; SE = standard error.",
general_title = "Note.")
회귀분석 결과 테이블 자동 생성: modelsummary
여러 모형을 한 테이블에 비교할 때 편리합니다.
install.packages("modelsummary")
library(modelsummary)
# 세 가지 모형 비교
m1 <- lm(mpg ~ wt, data = mtcars)
m2 <- lm(mpg ~ wt + hp, data = mtcars)
m3 <- lm(mpg ~ wt + hp + cyl, data = mtcars)
modelsummary(
list("Model 1" = m1, "Model 2" = m2, "Model 3" = m3),
# 표시할 통계량
statistic = "({std.error})", # 표준오차를 괄호 안에
stars = c("*" = .05, "**" = .01, "***" = .001),
# 모형 적합도 지표
gof_map = c("r.squared", "adj.r.squared", "AIC", "nobs"),
# 변수 이름 변경
coef_rename = c("wt" = "Weight",
"hp" = "Horsepower",
"cyl" = "Cylinders"),
title = "Comparison of Regression Models Predicting Fuel Efficiency"
)
Model 1 Model 2 Model 3
─────────────────────────────────────────
(Intercept) 37.285*** 37.227*** 38.752***
(1.878) (1.599) (1.787)
Weight -5.344*** -3.878*** -3.167***
(0.559) (0.633) (0.741)
Horsepower -0.032** -0.018
(0.009) (0.012)
Cylinders -0.942
(0.551)
─────────────────────────────────────────
R² 0.753 0.827 0.843
Adj. R² 0.745 0.815 0.826
AIC 166.029 156.649 158.035
Num.Obs. 32 32 32
─────────────────────────────────────────
* p < 0.05, ** p < 0.01, *** p < 0.001
# Word 파일로 내보내기
modelsummary(list(m1, m2, m3), output = "table_comparison.docx")
# LaTeX으로 내보내기
modelsummary(list(m1, m2, m3), output = "table_comparison.tex")
기술통계 테이블
# datasummary_skim으로 기술통계 테이블 자동 생성
datasummary_skim(mtcars[, c("mpg", "wt", "hp", "cyl")],
title = "Table 1. Descriptive Statistics")
# 그룹별 비교 테이블
mtcars$am_label <- factor(mtcars$am, labels = c("Automatic", "Manual"))
datasummary_balance(~ am_label,
data = mtcars[, c("mpg", "wt", "hp", "am_label")],
title = "Table 2. Descriptive Statistics by Transmission Type")
코드 한 줄로 테이블을 만들고, 데이터가 바뀌면 자동으로 업데이트됩니다. 수작업으로 숫자를 옮기다 발생하는 오류를 원천 차단할 수 있습니다.