4

I would like to dynamically create and knit .Rmd files and display outputs from analysis in browser. I'm using knitr and knit2html to do this. Currently I'm using the following approach:

myHTMLsummary <- function(data,x) {

  con <- paste0(getwd(),"/myHTMLSummary.Rmd")
  writeLines ("

Data frame summary
========================================================

Summary:
```{r,echo=FALSE}
summary(data[x])
```",con)

  knit2html(con,quiet=TRUE)

  if (interactive()) browseURL(paste0(getwd(),"/myHTMLSummary.html"))  
}

myHTMLsummary(iris,"Sepal.Length")

Are there better ways how to dynamically create and knit .Rmd files or this is the approach anyone is using?

Note: It would be quite cool to have HTML output tab in Rstudio to display results from such function directly (not in external browser). Maybe someone knows how to send results to Help tab?

lmo
  • 37,904
  • 9
  • 56
  • 69
Tomas Greif
  • 21,685
  • 23
  • 106
  • 155

1 Answers1

1

Maybe this is not a good example -- I do not think writeLines() is useful here. I mean the content is actually a fixed character string, so why not just save it to myHTMLSummary.Rmd in advance? Then you will only need

myHTMLsummary <- function(data, x) {
  knit2html("myHTMLSummary.Rmd", quiet=TRUE)
  if (interactive()) browseURL(file.path(getwd(), "myHTMLSummary.html"))  
}

myHTMLsummary(iris, "Sepal.Length")

I think what you really mean is to construct code chunks dynamically, i.e. the content of the source document is not fixed. In that case, see examples 075 and 021 in the knitr-examples repository. Note they are not the only approaches. You can use any string manipulation strategies to create your source document.

Regarding the RStudio question, you will have file a feature request to its developers. At the moment, I do not think it is possible to preview arbitrary HTML documents inside RStudio.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419