How to knit directly into an R object?

I would like to store the knit()

ted document directly in R as an R object, as a character vector.

I know I can do this by knit()

ing before tempfile()

and then importing the result, for example:

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

Is there a way to do this without using it tempfile()

and "pass" the result to a vector directly?


Why would I want this, you ask?

  • Line
  • *.tex

    will be programmatically saved to disk and subsequently transferred to PDF. Reading mapped *.tex

    from disk in downstream functions will make the code more complex.
  • Caching is much easier and moving that cache to another machine.
  • I'm just afraid of side effects in general and shenanigans filesystem in different machines / OS. I want to highlight them as little as possible ( print()

    , save()

    , plot()

    ) functions.

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

+3


source to share


2 answers


It should be as simple as one line:

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

      



You can read the help page again ?knitr::knit

to see what it returns.

+1


source


You can use con <- textConnection("varname", "w")

to create a connection that writes its output to a variable varname

and use output=con

in a call 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, except for a newline. Multiple lines will appear as different items knitted_obj

. I haven't timed it, but textual connections have a reputation for being slow, so it's not as fast as writing to the filesystem.

+1


source







All Articles