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

扶醉桌前 提交于 2021-01-28 13:55:08

问题


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.

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

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

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

How would I do this?

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

but failed with an error.

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?


回答1:


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)

Or, using the standalone document 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)



回答2:


One Solution would be to use tableGrob from gridExtra, add the table to a grid plot and save it with ggsave

require(ggplot2)
require(gridExtra)

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

This is quite simple but will be less convinient than a LaTeX solution for more complex tables.




回答3:


Here is a one-liner using the huxtable package (disclaimer: I am the author)

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

It will automatically open the PDF in your viewer – you can disable this with auto_open=FALSE.

For prettier formatting, create a huxtable object:

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


来源:https://stackoverflow.com/questions/55607205/how-to-export-an-xtable-as-pdf-directly-via-r-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!