How to knit directly to R object?

Viewed 110

I'd like to store a knit()ted document directly in R as an R object, as a character vector.

I know I can do this by knit()ing to a tempfile() and then import the result, like so:

library(knitr)
library(readr)
ex_file <- tempfile(fileext = ".tex")
knitr::knit(text = "foo", output = ex_file)
knitted_obj <- readr::read_file(ex_file)
knitted_obj

returns

# [1] "foo\n"

as intended.

Is there a way to do this without using a tempfile() and by directly "piping" the result to a vector?


Why on earth would I want this, you ask?

  • *.tex string will be programmatically saved to disc, and rendered to PDF later. Reading rendered *.tex from disc in downstream functions would make code more complicated.
  • Caching is just a whole lot easier, and moving this cache to a different machine.
  • I am just really scared of side effects in general and file system shenanigans across machines/OSes in particular. I want to isolate those to as few (print(), save(), plot()) functions as possible.

Does that make me a bad (or just OCD) R developer?

2 Answers
Related