Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Dynamic R Markdown Blocks

In my dataset, I have 60 groups that I want to analyze in put into an HTML report using R Markdown. Because I want to apply the same analysis to each group, I am hoping that there is a way I can dynamically generate the code blocks/analysis.

Simply, I want to avoid replicating the block 60 times.

I came across this this question which uses children in knitr. I have attempted to replicate this with the iris dataset. In my example below, all I wanted to do was generate three H4 titles, one for each species.

It's worth noting that I am not married to this approach, it just appears to be related to what I am looking to do.

Here are the files I used:

parent.RMD file. This would be my "master" report.

Automate Chunks of Analysis in R Markdown  ========================================================   ```{r setup, echo=FALSE} library(knitr) ```   ```{r run-numeric-md, include=FALSE} out = NULL for (i in as.character(unique(iris$Species))) {   out = c(out, knit_child('child.Rmd')) } 

```

And here is child.Rmd.

#### Species = `r [i]` 
like image 675
Btibert3 Avatar asked Feb 12 '14 13:02

Btibert3


People also ask

How do you make a R chunk?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

What happens when you knit an R Markdown file?

There are two ways to render an R Markdown document into its final output format. If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it. Note that both methods use the same mechanism; RStudio's “Knit” button calls rmarkdown::render() under the hood.

What is knitr R Markdown?

RMarkdown is an extension to markdown which includes the ability to embed code chunks and several other extensions useful for writing technical reports. The rmarkdown package extends the knitr package to, in one step, allow conversion between an RMarkdown file (.Rmd) into PDF, HTML, word document, amongst others.


1 Answers

Try knit_expand():

Automate Chunks of Analysis in R Markdown  ========================================================  ```{r setup, echo=FALSE} library(knitr) ```  ```{r run-numeric-md, include=FALSE} out = NULL for (i in as.character(unique(iris$Species))) {   out = c(out, knit_expand(text='#### Species = {{i}}')) } ```  `r paste(knit(text = out), collapse = '\n')` 

You can also create a template file like 'child.rmd' and put this in your for loop so you don't have to put a complicated analysis in quotes:

out = c(out, knit_expand('template.rmd')) 

Then have your 'template.rmd' be:

#### Species = {{i}} 
like image 196
Sam Dickson Avatar answered Oct 03 '22 00:10

Sam Dickson