I'm creating a document in which I repeat the same formatting multiple times. So I want to automate the process using the for
loop in R. Here's a simple example.
Assume, I have an R code that computes some information for all cut
values in ggplot2::diamonds
dataset, which I want then to print in my document in five separate sections (one section per cut):
library(knitr); library(data.table)
dt <- data.table(ggplot2::diamonds)
for (cutX in unique(dt$cut)) {
dtCutX <- dt[cut==cutX, lapply(.SD,mean), .SDcols=5:7]
#### START of the Rmd part that needs to be printed
# Section: The Properties of Cut `cutX`
<!-- NB: This is the Section title in Rmd format, not the comment in R format ! -->
This Section describes the properties of cut `r cutX`. Table below shows its mean values:
`r knitr::kable(dtCutX)`
The largest carat value for cut `r cutX` is `r dt[cut=='Ideal', max(carat)]`
#### END of the Rmd part that needs to be printed
}
How do I do that?
I.e., How do I insert inside my main Rmd code an R code that tells it to insert other Rmd codes (in a for loop) - to produce automatically five Sections for five types of diamond cuts?
PS.
I found these related posts:
Reusing chunks in Knitr and
Use loop to generate section of text in rmarkdown
but was not able yet to recreate the solution for the above example.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…