maxheld maxheld - 3 years ago 81
R Question

How to knit directly to R object?

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?

Answer Source

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. 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download