如何通过R脚本直接将xtable导出为PDF? [英] How to export an xtable as PDF directly via R script?

查看:119
本文介绍了如何通过R脚本直接将xtable导出为PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.frame,它是科学海报的漂亮PDF表格.尽管通过pdf()导出图非常容易,但是我对这张表很执着.

I have a data.frame that I need as a nice PDF table for a scientific poster. While it's very easy to export plots via pdf(), I'm stuck with this table.

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

I know how to get a PDF table with rmarkdown, e.g.

---
output: pdf_document
---

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

但是我想要直接 从R脚本中获得此输出,例如

But I want this output directly from the R script, e.g.

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

我该怎么做?

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

So far I attempted this code with a indirection via 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

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

I guess there's probably an easier solution?

推荐答案

在没有rmarkdown的情况下,这是一种可能.

Here is a possibility, without 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)

这篇关于如何通过R脚本直接将xtable导出为PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆