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

问题描述 投票:0回答:1

我一直试图让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。

经过几个小时的试验和错误,我发现了如何,并发布下面的代码以防其他人。

r latex r-markdown knitr hmisc
1个回答
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)

```
© www.soinside.com 2019 - 2024. All rights reserved.