Search code examples
rlatexknitrsweavehmisc

Latex math mode in Hmisc variable labels using compareGroups table


I want to produce a number of tables for the same set of variables. I use the wonderful R package compareGroups and Hmisc to assign variable labels so that I don't have to change variable names for each table. Some variable names include latex math mode but this gives me an error because compareGroups exports $that$ like this: \$that\$. Here is a minimal 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 to avoid that a \ is inserted before $ by export2latex? Or any workaround?


Solution

  • I received a message from compareGroups forum (link) withan easy solution. You could also just substitute "\$" with "$" using sub function:

    tab <- export2latex(tab)
    sub("\\$","$", 
        tab, 
        fixed=TRUE, 
        perl=FALSE)