gtsummary icon indicating copy to clipboard operation
gtsummary copied to clipboard

Feature request: as_kable_extra(): translate line breaks in Beta coefficient cells using makecell

Open viola-hilbert opened this issue 1 year ago • 1 comments

Problem I would like to export tbl_regression() objects to LaTeX, using as_kable_extra() and the qjecon theme, where beta coefficients are reported with standard errors under the coefficients in brackets. Here is a MWS with the standard theme (one could also just set the qjecon theme and leave out lines 5-8 in the code below):

library(gtsummary)

lm(mpg ~ drat, data = mtcars) |>
  tbl_regression() |>
  modify_header(estimate ~ "**Beta**  \n**(SE)**") |> 
  add_significance_stars(
    pattern = "{estimate}{stars}  \n({std.error})"
  ) |>
  as_kable_extra(format = "latex", booktabs = T)

This yields the following latex code:

\begin{tabular}{lc}
\toprule
\textbf{Characteristic} & \makecell[c]{\textbf{Beta}\ \ \\\textbf{(SE)}}\\
\midrule
drat & 7.7***\ \ (1.51)\\
\bottomrule
\multicolumn{2}{l}{\rule{0pt}{1em}\textsuperscript{1} \textit{p<0.05; \textbf{p<0.01; }}p<0.001}\\
\end{tabular}

Although the gtsummary line break pattern is specified in the same way for the header and the coefficient cells (" \n"), this results in a different LaTeX translation for the header vs. coefficient cell. This LaTeX code will result in an actual line break in the header, if the makecell package is loaded. The line breaks in the coefficient cells are not translated using makecell, so the standard errors will appear in the same line as the coefficients.

Suggested solution I would like the "{estimate}{stars} \n({std.error})" pattern to be translated using the makecell package. Alternatively, the standard errors could be translated as a new line -- this is what outreg2 package to export Stata regression results to LaTeX does (to the best of my knowledge).

Possible alternatives I saw a quick fix suggested on stackoverflow, but this would cause problems with special characters and would not work with tbl_merge().

viola-hilbert avatar Dec 05 '23 11:12 viola-hilbert

Thank you for the post @viola-hilbert and all the details!

FYI, I probably won't have a chance to look into this anytime soon. In the meantime, perhaps one of the other latex engines will work: gt, huxtable

ddsjoberg avatar Dec 08 '23 15:12 ddsjoberg