Hmisc labels including latex math mode

31 views
Skip to first unread message

rapp...@gmail.com

unread,
Jan 11, 2017, 7:07:38 AM1/11/17
to compareGroups Forum
Thanks for your wonderful package! I have a question though:
I would like to produce latex tables using export2latex. I assigned Hmisc-variable labels so that I don't have to edit the variable names for each table, separately. The labels include latex math mode in $$ and export2latex unfortunately compiles the sign "$" as "\$". Here is a little example:
#####################################################
# assigning Hmisc label includinc math mode in $$
library(Hmisc)
label(mtcars$mpg) <- "[$\\frac{miles}{gallon}$]"

# descriptive table of mpg by am
library(compareGroups)

tab <- createTable(
compareGroups(data = mtcars,
am ~ mpg)
)

# in createTable, the variable name looks fine
tab

# when exported to latex, a \ is inserted before each $
export2latex(tab)
#####################################################
Is there a way out?
Thank you so much for your help!

compareGroups

unread,
Jan 12, 2017, 3:12:40 AM1/12/17
to compareGroups Forum
This is a little tricky. The error happens because export2latex function insert "\" scape character before some special characters such as "$". So, you have to remove these "\".
First, call export2latex function and store its result to an object, which will be a text with latex code to generate the descriptive table. 
Then, substitute "\$" by "$".
Below there is an example with a reproducible code in R markdown.
Hope it helps.

---
title: "Example"
author: "Isaac"
output: pdf_document
header-includes:
  - \usepackage{longtable}
  - \usepackage{multicol}
  - \usepackage{multirow}
  - \usepackage{float}
  - \usepackage{lscape} 
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, comment="",warning=FALSE,message=FALSE)
```

```{r}
# assigning Hmisc label includinc math mode in $$
library(Hmisc)
label(mtcars$mpg) <- "$\\frac{miles}{gallon}$"
# descriptive table of mpg by am
library(compareGroups)
tab <- createTable(compareGroups(am ~ mpg, data = mtcars))
```

\newpage


```{r,results="hide"}
temp <- export2latex(tab)[[1]]
temp <- sub("\\$\\frac{miles}{gallon}\\$","$\\frac{miles}{gallon}$",temp,fixed=TRUE,perl=FALSE)
```

```{r,results="asis"}
cat(temp)
```
 
Reply all
Reply to author
Forward
0 new messages