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

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

我有一个data.frame,我需要作为科学海报的漂亮的PDF表。虽然很容易通过pdf()导出地块,但我仍然坚持使用这张桌子。

我知道如何获得带有rmarkdown的PDF表格,例如

---
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

我想这可能是一个更简单的解决方案?

r pdf knitr xtable
3个回答
2
投票

这是一种可能性,没有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文档类:

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)

1
投票

一个解决方案是使用来自tableGrobgridExtra,将表格添加到网格图并使用ggsave保存

require(ggplot2)
require(gridExtra)

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

这非常简单,但对于更复杂的表格而言,它不如LaTeX解决方案更方便。


0
投票

这是使用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)
© www.soinside.com 2019 - 2024. All rights reserved.