I am using R / Rmarkdown / knitr to generate multiple reports (pdfs) via render(), but the content / length of the reports will vary depending on certain characteristics of the underlying data.
As an example, let's say I have 10 different datasets of 50 variables each and I'm examining a correlation matrix of all 50 variables in the data. I want to produce a report for each dataset that has a new page for each variable pair that has a correlation that is greater than 0.5 and each variable pair that has a correlation that is less than -0.5. The number of correlations that will meet these thresholds will vary by dataset, and thus the report length / number of pages will vary by dataset.
I've learned to use {asis, echo = somecondition, eval = somecondition} to evaluate whether an entire section needs to be included (e.g., when there are no negative correlations less than -0.5). I have also seen solutions utilizing 'for' loops when there might be variable-length arguments across reports, but those solutions don't include printing each result on a new page. I'd also like to include section headers on each of the pages reporting the correlations as well.
The difficulty for me is that any solution I can think of requires nesting chunks of text and r code within one another. For some sample Rmd code of how I am approaching the problem, I've tried to print a new histogram for each small dataset on a new page, using "```" to denote where three ticks would usually be as to not mess up the sample code formatting:
"```"{r, echo = FALSE}
datlist <- list(df1 = rnorm(100), df2 = rnorm(100), df3 = rnorm(100)) # fake data
"```"
Some Text Introducing the Report
"```"{'asis', eval = length(datlist) > 0} # evaluating if the section is to be included
"```"{r, echo = FALSE, eval = length(datlist) > 0}
for(i in 1:length(datlist)){ # starting the variable-length scope
"```"{'asis', eval = length(datlist) > 0} # the information to be included on each new page
\newpage
\section{`r (names(datlist[i]))`}
Here is a histogram of the data found in `r (names(datlist[i]))`.
`r hist(unlist(datlist[i]))`
"```"
} # closing the for loop above
"```"
"```"
Any help, including a solution using a completely different approach, is most welcome.