Skip to content

Instantly share code, notes, and snippets.

@kylebutts
Last active December 7, 2020 23:26
Show Gist options
  • Save kylebutts/dddef300dd882052e0caa9769b698c5b to your computer and use it in GitHub Desktop.
Save kylebutts/dddef300dd882052e0caa9769b698c5b to your computer and use it in GitHub Desktop.
library(texreg)
extract_body <- function(gt) {
if(inherits(gt, "gt_tbl")) gt <- as.character(gt::as_latex(gt))
stringr::str_match(gt, "(?s)\\\\midrule\\n(.*)\\\\bottomrule")[[2]]
}
df <- tibble(
treat = 1:20 > 10,
z = runif(20, -1, 1),
y = 5 * treat + 3 * z + 2 + rnorm(20, 0, 1^2)
)
m1 <- lm(y ~ treat, data = df)
m2 <- lm(y ~ treat + z, data = df)
texreg::texreg(
list(m1, m2),
booktabs = TRUE,
custom.coef.names = c("Intercept", "Treated", "Covariate")
) %>%
extract_body() %>%
cat()
@kylebutts
Copy link
Author

extract_body <- function(gt) {
    if(inherits(gt, "gt_tbl")) gt <- as.character(gt::as_latex(gt))
    stringr::str_match(gt, "(?s)\\\\midrule\\n(.*)\\\\bottomrule")[[2]]
} 

library(tidyverse, warn.conflicts = FALSE)
#> Warning: replacing previous import 'vctrs::data_frame' by 'tibble::data_frame'
#> when loading 'dplyr'

df <- tibble(
    treat = 1:20 > 10,
    z = runif(20, -1, 1),
    y = 5 * treat + 3 * z + 2 + rnorm(20, 0, 1^2)
)

m1 <- lm(y ~ treat, data = df)
m2 <- lm(y ~ treat + z, data = df)

texreg::texreg(
    list(m1, m2), 
    booktabs = TRUE,
    custom.coef.names = c("Intercept", "Treated", "Covariate"),
    include.rsquared = F
) %>% 
    extract_body() %>% 
    cat()
#> Intercept  & $1.95^{**}$  & $2.55^{***}$ \\
#>            & $(0.55)$     & $(0.28)$     \\
#> Treated    & $4.92^{***}$ & $3.87^{***}$ \\
#>            & $(0.78)$     & $(0.41)$     \\
#> Covariate  &              & $3.04^{***}$ \\
#>            &              & $(0.40)$     \\
#> \midrule
#> Adj. R$^2$ & $0.67$       & $0.92$       \\
#> Num. obs.  & $20$         & $20$         \\

Created on 2020-12-07 by the reprex package (v0.3.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment