R markdown repeat the same part of the report with a different parameter

I am familiar with the R markdown options.

However, let's say I want to create the same report (the same graph, the same table), but for 5 different regions.

Is there a way to do this gracefully in a loop or foot or do I need to make several sections. So in the pseudocode, I want to do something like:

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

Instead

 bunch of text table[1] plot[1] bunch of text table[2] plot[2] ... 

In other words, I want to function a β€œsection” of the report, and then I can call

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

And he will go in, put the text, numbers, etc., associated with the index i.

+5
source share
1 answer

You must explicitly call print if inside the 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

Since Stefan Laurent has already demonstrated in Dynamic number of calls per piece with a book

you can define a child element of .rmd:

test_section.rmd

 Header: `ri`-th cars ```{r} print(summary(cars[,-i])) plot(cars[,-i]) ``` 

and in the main rmd file, combine 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')` 
+3
source

All Articles