How to knit directly to R object?

2019-07-02 01:47发布

问题:

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?

回答1:

It should be as straightforward as a single line like this:

knitted_obj = knitr::knit(text = "foo")

You may want to read the help page ?knitr::knit again to know what it returns.



回答2:

You can use con <- textConnection("varname", "w") to create a connection that writes its output to variable varname, and use output=con in the call to knit(). For example:

library(knitr)
con <- textConnection("knitted_obj", "w")
knit(text="foo", output = con)
close(con)
knitted_obj

returns the same as your tempfile approach, except for the newline. Multiple lines will show up as different elements of knitted_obj. I haven't timed it, but text connections have a reputation for being slow, so this isn't necessarily as fast as writing to the file system.



标签: r pipe latex knitr