knitr::opts_chunk$set(echo = TRUE)

\vspace{1cm}

sjPlot::tab_model() is wonderful to create beautiful tables for your statistical analysis but, afaik, it is not possible to easily save the output html tables as tex or pdf documents, or include them in Rmd documents.

In the html2latex repo there are two functions to help you simplify the process.

tab_model() html tables to tex and pdf

Using html2pdf() with an html table will create a tex file. The build_pdf parameter builds a pdf using that tex file.

library(html2latex)
library(lme4)
library(sjPlot)

# This is a terrible model
model = lmer(mpg ~ cyl * disp + (1|vs), mtcars)

# We save the sjPlot table to an .html file
sjPlot::tab_model(model, file = "temp.html")

# Create tex and pdf
# This readme was knitted on a Mac, therefore mac = TRUE
html2pdf(filename = "temp.html", table_width = 13, silent = TRUE, style = TRUE, build_pdf = TRUE, mac = TRUE, clean = TRUE)
library(html2latex)
library(lme4)
library(sjPlot)

# This is a terrible model
model = lmer(mpg ~ cyl * disp + (1|vs), mtcars)

# We save the sjPlot table to an .html file
table = sjPlot::tab_model(model, file = "temp.html")

# Create tex
html2pdf(filename = "temp.html", table_width = 13, build_pdf = TRUE, silent = TRUE)

\newpage

tab_model() html tables in a Rmd document

You can include tab_model() table in a Rmarkdown pdf in three steps:

1. YAML header

The YAML heather of the .Rmd document must include this:

header-includes:
- \usepackage{array}
- \usepackage{longtable}
- \newcommand\textstyleStrongEmphasis[1]{\textbf{#1}}
- \makeatletter
- \newcommand\arraybslash{\let\\\@arraycr}

2. Extract the table bit from the tex file

The tex file created with html2pdf can be rendered as a pdf by opening the tex file in Rstudio and using the Compile PDF button. But if you want to use the table code (from \begin{longtable} to \end{longtable}), we need to extract it first.

# Create table.txt to be able to use it in Rmd documents
tex2Rmd("temp.tex")

# File with table code created in: table.txt

3. Use this code in the Rmd document.

Finally, you need to insert the latex code below outside of a chunk in your Rmd file.

\newcommand{\myinput}[1]{%
  \begingroup%
  \renewcommand\normalsize{\small}% Specify your font modification
  \input{#1}%
  \endgroup%
}
\begin{centering}
\myinput{table.txt}
\end{centering}

And the result will look like this:

\newcommand{\myinput}[1]{% \begingroup% \renewcommand\normalsize{\small}% Specify your font modification \input{#1}% \endgroup% } \begin{centering} \myinput{table.txt} \end{centering}


Manually input latex code

Alternativelly, you can manually insert the contents of table.txt in a chunk staring with ```{=latex}

See: https://bookdown.org/yihui/rmarkdown-cookbook/raw-latex.html



gorkang/html2latex documentation built on Aug. 5, 2023, 3:47 a.m.