Skip to content

Instantly share code, notes, and snippets.

@kylebutts
Last active December 7, 2020 23:16
Show Gist options
  • Save kylebutts/c0857c7c9f176636f50f197056e63791 to your computer and use it in GitHub Desktop.
Save kylebutts/c0857c7c9f176636f50f197056e63791 to your computer and use it in GitHub Desktop.
Extract Latex body from gt table
#' Requires gt::gt() object or gt::as_latex() object and returns just the body of the gt table
extract_body_gt <- 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)
library(gt, warn.conflicts = FALSE)
# HTML
head(mtcars) %>%
gt() %>%
gt::as_raw_html()
# Latex Body
head(mtcars) %>%
gt() %>%
extract_body_gt() %>%
cat()
# cat(., file = "*/*.tex)
@kylebutts
Copy link
Author

kylebutts commented Dec 7, 2020

Requires gt::gt() object or gt::as_latex() object and returns just the body of the gt table

extract_body_gt <- 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'
library(gt, warn.conflicts = FALSE)

# HTML
head(mtcars) %>% 
    gt() %>% 
    gt::as_raw_html()
mpg cyl disp hp drat wt qsec vs am gear carb
21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
# Latex Body
head(mtcars) %>%
    gt() %>% 
    extract_body_gt() %>% 
    cat()
#> 21.0 & 6 & 160 & 110 & 3.90 & 2.620 & 16.46 & 0 & 1 & 4 & 4 \\ 
#> 21.0 & 6 & 160 & 110 & 3.90 & 2.875 & 17.02 & 0 & 1 & 4 & 4 \\ 
#> 22.8 & 4 & 108 & 93 & 3.85 & 2.320 & 18.61 & 1 & 1 & 4 & 1 \\ 
#> 21.4 & 6 & 258 & 110 & 3.08 & 3.215 & 19.44 & 1 & 0 & 3 & 1 \\ 
#> 18.7 & 8 & 360 & 175 & 3.15 & 3.440 & 17.02 & 0 & 0 & 3 & 2 \\ 
#> 18.1 & 6 & 225 & 105 & 2.76 & 3.460 & 20.22 & 1 & 0 & 3 & 1 \\

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