在Knitr Markdown中使用R Hmisc summary / summaryM Latex命令pdf

时间:2019-04-15 01:44:46

标签: r latex r-markdown knitr hmisc

我一直在尝试使Hmisc latex.summarylatex.summaryM示例在RStudio中使用Knitr创建的pdf文档中工作。但是,请继续获取错误消息。示例数据为:

options(digits=3)
set.seed(173)
sex <- factor(sample(c("m","f"), 500, rep=TRUE))
country <- factor(sample(c('US', 'Canada'), 500, rep=TRUE))
age <- rnorm(500, 50, 5)
sbp <- rnorm(500, 120, 12)
label(sbp) <- 'Systolic BP'
units(sbp) <- "mmHg"
treatment <- factor(sample(c("Drug","Placebo"), 500, rep=TRUE))
sbp[1] <- NA


# Generate a 3-choice variable; each of 3 variables has 5 possible levels
symp <- c('Headache','Stomach Ache','Hangnail',
          'Muscle Ache','Depressed')
symptom1 <- sample(symp, 500,TRUE)
symptom2 <- sample(symp, 500,TRUE)
symptom3 <- sample(symp, 500,TRUE)
Symptoms <- mChoice(symptom1, symptom2, symptom3, label='Primary Symptoms')

我想创建一个包含表格的pdf文档

tab1 <- summary(sex ~ treatment + Symptoms, fun=table)
tab2 <- summaryM(age + sex + sbp + Symptoms ~ treatment,
          groups='treatment', test=TRUE)

我正在运行R版本3.5.2(2018-12-20),RStudio 1.1.463,Hmisc_4.2-0,并已使用tinytex::install_tinytex()安装tinytex。

经过几个小时的反复试验,我发现了如何做,并在下面发布了代码,以防其他人得到帮助。

1 个答案:

答案 0 :(得分:1)

注意,以下代码对我有用;

使用relsize属性防止出现以下Hmisc::units错误时对failed to compile乳胶包装的要求。

! Undefined control sequence.
<recently read> \smaller

mylatex函数取自https://stackoverflow.com/a/31443576/4241780,对于删除不需要的输出是必需的。

需要使用选项file = ""来防止错误

Error in system(comd, intern = TRUE, wait = TRUE) : 'yap' not found 
Calls: <Anonymous> ... print -> print.latex -> show.latex -> show.dvi -> system

使用where = "!htbp"选项可确保将表保留在其放置位置,并且不会浮动到页面顶部(默认为where = "!tbp"https://tex.stackexchange.com/a/2282

---
title: "Untitled"
author: "Author"
date: "15 April 2019"
output: 
  pdf_document: 
     extra_dependencies: ["relsize"]
---

```{r setup, include=FALSE}

library(Hmisc)
library(dplyr)

mylatex <- function (...) {
    o <- capture.output(latex(file = "", where = "!htbp", ...))
    # this will strip /all/ line-only comments; or if you're only
    #  interested in stripping the first such comment you could
    #  adjust accordingly
    o <- grep('^%', o, inv=T, value=T)
    cat(o, sep='\n')
}

```

```{r data}

# As in question above ...

```

Here is the first table

```{r tab1, results = "asis"}

tab1 <- summary(sex ~ treatment + Symptoms, fun=table)

mylatex(tab1)

```

Here is the second table

```{r tab2, results = "asis"}

tab2 <- summaryM(age + sex + sbp + Symptoms ~ treatment, test=TRUE)

mylatex(tab2)

```