Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R markdown rerun the same section of report with different parameter

Tags:

r

r-markdown

I'm familiar with R markdown "parameters".

However, say I want to generate the same report (same chart, same table) but for 5 different regions.

Is there a way to do this elegantly in a loop or lapply or do I need to make several sections. So in pseudo code I want to do something like:

for(i in 1:5):
   Bunch of text
   table[i]
   plot[i]

Instead of

bunch of text
table[1]
plot[1]

bunch of text
table[2]
plot[2]

...

Put another way, I want to functionalize a "section" of the report, and then I can call

for(i in 1:5):
   makeReport(i)

And it will go in, put in the text, figures, etc associated with index i.

like image 539
user1357015 Avatar asked Oct 20 '22 09:10

user1357015


1 Answers

You have to call print explicitly if inside for loop:

```{r}
for(i in 1:2) {
  print(summary(cars[,-i]))
  plot(cars[,-i])
}
```

or

```{r}
makeReport <- function(i) {
  print(summary(cars[,-i]))
  plot(cars[,-i])
}

for(i in 1:2) {
  makeReport(i)
}
```

Update

As Stéphane Laurent already demonstrated in Dynamic number of calls to a chunk with knitr

you can define a child .rmd:

test_section.rmd

Header: `r i`-th cars

```{r}
  print(summary(cars[,-i]))
  plot(cars[,-i])
```

and in the main rmd file concatenate the results:

```{r runall, include=FALSE}
out <- NULL
for (i in 1:2) {
  out <- c(out, knitr::knit_child('test_section.rmd'))
}
```

`r paste(out, collapse = '\n')` 
like image 191
bergant Avatar answered Oct 22 '22 01:10

bergant