How to knit directly to R object?

廉价感情. 提交于 2019-12-12 12:44:05

问题


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.



来源:https://stackoverflow.com/questions/45321041/how-to-knit-directly-to-r-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!