Search code examples
rpdfknitrxtable

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


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?


Solution

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