How to use an object rather than a file as source for knitting [resolved]


#1

Hi

Let’s say that I create a character object in which I store pure markdown strings. Is there a way to knit this object from within the current environment?

Thanks


#2

Hi, you could have a look at the knitr::spin function. See https://deanattali.com/2015/03/24/knitrs-best-hidden-gem-spin/


#3

Thanks for the tip.

spin seems to be able to work on object and file. However, it is not obvious from the documentation how to make it work with an object.


require(knitr)
markobj <- c('---',
             'title: "test"',
             'output: html_document',
             '---',
             '',
             '## R Markdown',
             '',
             'This is an R Markdown document.')

knit2html(spin(text=markobj, format='Rmd'), output = './test.html')

returns a lot of errors.

Any ideas?


#4

An absolute worst case would be to write out a file to be knit based on the object, render that file, then delete it. I say worst case because it seems round about, but works. Whatever improvements to the process people come up with, you have at least got a working baseline.


#5

knit(input = textConnection(object))


#6

This worked for me:

markobj <- c(
  '---',
  'title: "test"',
  'output: html_document',
  '---',
  '',
  '## R Markdown',
  '',
  'This is an R Markdown document.'
)

## knit lines into Rmd formatted object
txt <- knitr::knit(text = markobj)

## convert to html file
markdown::markdownToHTML(text = txt, output = "test.html")

## open file in browser
browseURL("test.html")

#7

Thanks, this works great. It even recognizes objects previously declared.

a <- 1:5
markobj <- c('---',
             'title: "test"',
             'output: html_document',
             '---',
             '',
             '## R Markdown',
             '',
             'This is an R Markdown document.',
             '```{r}',
             'b <- 11:15',
             'print(a)',
             'print(b)',
             '```')

markdown::markdownToHTML(text = knitr::knit(text = markobj), output = 'test.html')

browseURL("test.html")

Creating markdown reports within a function