使用compareGroups表

时间:2017-01-11 10:20:17

标签: r latex knitr sweave hmisc

我想为同一组变量生成许多表。我使用精彩的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之前插入\?或者任何解决方法?

2 个答案:

答案 0 :(得分:2)

这是一种使用pixiedust生成表格的变通方法。 pixiedust可以选择&#34;清理&#34;通过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()
```

enter image description here

如果您希望更轻松地触摸它,可以扩展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()

答案 1 :(得分:0)

我收到了来自compareGroups论坛(link)的消息,并提供了简单的解决方案。您也可以替换&#34; \ $&#34;用&#34; $&#34;使用sub函数:

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