【问题标题】:Latex math mode in Hmisc variable labels using compareGroups table使用 compareGroups 表的 Hmisc 变量标签中的乳胶数学模式
【发布时间】:2017-05-26 02:01:20
【问题描述】:

我想为同一组变量生成多个表。我使用出色的 R 包 compareGroups 和 Hmisc 来分配变量标签,这样我就不必为每个表更改变量名。一些变量名包括乳胶数学模式,但这给了我一个错误,因为 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 在$ 之前插入一个\?或者有什么解决方法?

【问题讨论】:

  • 恐怕这似乎被硬编码为export2latex.createTable。似乎没有关闭它的选项。

标签: r latex knitr sweave hmisc


【解决方案1】:

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

解决方案以 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()

【讨论】:

    【解决方案2】:

    我收到了来自 compareGroups 论坛 (link) 的消息,提供了一个简单的解决方案。您也可以使用 sub 函数将“\$”替换为“$”:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      相关资源
      最近更新 更多