使用 compareGroups table 的 Hmisc 变量标签中的 Latex 数学模式

Latex math mode in Hmisc variable labels using compareGroups table

我想为同一组变量生成多个 table。我使用很棒的 R 包 compareGroups 和 Hmisc 来分配变量标签,这样我就不必为每个 table 更改变量名称。一些变量名称包括乳胶数学模式,但这给了我一个错误,因为 compareGroups 导出 $that$ 是这样的:$that$。这是一个最小的例子:

# 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)

有没有办法避免export2latex在$之前插入\?或者任何解决方法?

这是一个使用 pixiedust 生成 table 的解决方法。 pixiedust 可以选择通过 Hmisc::latexTranslate "sanitize" 单元格的内容。默认情况下,此选项处于关闭状态。

解决方案以 Rmd 文件的形式给出

---
title: "Untitled"
output: pdf_document
header-includes: 
- \usepackage{amssymb} 
- \usepackage{arydshln} 
- \usepackage{caption} 
- \usepackage{graphicx} 
- \usepackage{hhline} 
- \usepackage{longtable} 
- \usepackage{multirow} 
- \usepackage[dvipsnames,table]{xcolor} 
---

```{r, include = FALSE}
library(Hmisc)
library(compareGroups)
library(broom)
library(magrittr)
library(pixiedust)
```

```{r}
label(mtcars$mpg) <- "[$\frac{miles}{gallon}$]"

# descriptive table of mpg by am
tab <- createTable(
  compareGroups(data = mtcars, 
                gear ~ mpg + qsec)
)

tab_df <- 
  tab$descr %>%
  tidy()

tab_head <- 
  c("", attr(tab, "ylevels"), "p.overall",
    "", sprintf("N=%s", tab$avail[1, -c(1, (ncol(tab$avail) - 0:1))]), "") %>%
  matrix(nrow = 2, 
         byrow = TRUE) %>%
  tidy %>%
  setNames(names(tab_df))

dust(tab_df,
     float = FALSE) %>%
  redust(tab_head, part = "head") %>%
  medley_bw()
```

如果你想让它更简单,你可以扩展 dust 方法来包含一个 dust.createTable 方法(这是原始的,我还没有考虑所有的用例, 但例如)

dust.createTable <- function(object, ...){
  obj_df <- 
    object$descr %>%
    broom::tidy()

  obj_head <- 
    c("", attr(object, "ylevels"), "p.overall",
      "", sprintf("N=%s", object$avail[1, -c(1, (ncol(object$avail) - 0:1))]), "") %>%
    matrix(nrow = 2, 
           byrow = TRUE) %>%
    broom::tidy() %>%
    stats::setNames(names(obj_df))

  pixiedust::dust(obj_df) %>%
    pixiedust::redust(obj_head, part = "head")
}


compareGroups(data = mtcars,
            gear ~ mpg + qsec) %>%
  createTable() %>%
  dust()

compareGroups(data = mtcars,
              gear ~ mpg + qsec + wt) %>%
  createTable() %>%
  dust()

我从 c​​ompareGroups 论坛 (link) 收到一条消息,其中包含一个简单的解决方案。您也可以使用 sub 函数将“\$”替换为“$”:

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