如何直接通过 R 脚本将 xtable 导出为 PDF?

How to export an xtable as PDF directly via R script?

我有一个 data.frame 需要作为科学海报的精美 PDF table。虽然通过 pdf() 导出绘图非常容易,但我仍然坚持使用 table。

我知道如何使用 rmarkdown 获取 PDF table,例如

---
output: pdf_document
---

```{r tab, echo=FALSE, results='asis'}
library(xtable)
xtable(head(mtcars))
```

但我想 直接从 R 脚本输出,例如

renderThisToPDF(xtable(head(mtcars), to="nicetable.pdf")  # fantasy code

我该怎么做?

到目前为止,我尝试通过 writeLines

间接访问此代码
code <- "library(xtable)\nprint(xtable(head(mtcars)))"

fileConn <- file("output.Rmd")
writeLines(cat("---\noutput: pdf_document\n---\n```{r tab, echo=FALSE, results='asis'}\n", 
               code, "\n```\n"), fileConn)
close(fileConn)

knitr::knit('output.Rmd')

但因错误而失败。

Error in writeLines(cat("---\noutput: pdf_document\n---\n```{r tab, echo=FALSE,
                        results='asis'}\n",  : 
                          can only write character objects

我想可能有更简单的解决方案?

一个解决方案是使用 gridExtra 中的 tableGrob,将 table 添加到网格图中并使用 ggsave

保存
require(ggplot2)
require(gridExtra)

ds <- iris[1:10, ]
tg <- tableGrob(ds)
ggsave("test.pdf", tg)

这很简单,但对于更复杂的 tables 来说,不如 LaTeX 解决方案方便。

有一种可能,没有 rmarkdown

library(xtable)
latex <- print.xtable(xtable(head(iris)), print.results = FALSE)

writeLines(
  c(
    "\documentclass[12pt]{article}",
    "\begin{document}",
    "\thispagestyle{empty}",
    latex,
    "\end{document}"
  ),
  "table.tex"
)

tools::texi2pdf("table.tex", clean = TRUE)

或者,使用 standalone 文档 class:

latex <- print.xtable(xtable(head(iris)), print.results = FALSE, 
                      floating = FALSE)
writeLines(
  c(
    "\documentclass[12pt]{standalone}",
    "\usepackage{caption}",
    "\begin{document}",
    "\minipage{\textwidth}",
    latex,
    "\captionof{table}{My caption}",
    "\endminipage",
    "\end{document}"
  ),
  "table.tex"
)
tools::texi2pdf("table.tex", clean = TRUE)

这是使用 huxtable 包的单行代码(免责声明:我是作者)

huxtable::quick_pdf(iris[1:10, ])

它会在您的查看器中自动打开 PDF – 您可以使用 auto_open=FALSE 禁用它。

为了更漂亮的格式,创建一个 huxtable 对象:

library(huxtable)
ht <- as_hux(iris[1:10, ])
bold(ht)[1,] <- TRUE       # or whatever else you feel like doing
quick_pdf(ht)