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

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

1 Like

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

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?

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.

knit(input = textConnection(object))

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")
2 Likes

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")
2 Likes