0

I have a large Rmd document which I am condensing using collapsible sections, i.e.:

<details>
    <summary>Dropdown Heading</summary>
</details>

I now want to run a section of code where it pulls data from each column of a df performs some analysis and produces a plot. The df has 20+ columns, so ideally what I need is that within my for loop the code also adds in these collapsible sections so that in the end I have 20+ new collapsible sections.

If I was to write an example out the long way:

'''{r}
df <- data.frame(a=c(0,1,2,3,4), 
                 b=c(10,11,12,13,14),
                 c=c(20,21,22,23,24))
'''

<details>
    <summary>Dropdown Heading for 'a'</summary>

'''{r}
ggplot(df, aes(x = a, y=c(1,2,3,4,5))) + geom_point()
'''

</details>



<details>
    <summary>Dropdown Heading for 'b'</summary>

'''{r}
ggplot(df, aes(x = b, y=c(1,2,3,4,5))) + geom_point()
'''

</details>
... etc

As can be seen from simplified example above, this would get very long with 20+ columns. However, I would like to be able to do something like:

'''{r}
df <- data.frame(a=c(0,1,2,3,4), 
                 b=c(10,11,12,13,14),
                 c=c(20,21,22,23,24))

cat("<details>\n")
cat(paste0("<summary>Dropdown Heading for ", col_name, "</summary>\n"))

for (col_name in colnames(df)){
  ggplot(df, aes(x = .data[[col_name]], y=c(1,2,3,4,5))) + geom_point()

cat("</details>\n")
}
'''

However, I can not find a way to do this. Is this possible within RMD files?


SOLUTION

Thanks to @MrFlick for the pointer

'''{r echo = TRUE, results = "asis"}
df <- data.frame(a=c(0,1,2,3,4), 
                 b=c(10,11,12,13,14),
                 c=c(20,21,22,23,24))

template_start <- "<details>
\t<summary>Dropdown Heading for %s </summary>

Test text

" # don't forget the newline

template_end = "</details>

"

for (col_name in colnames(df)){
  cat(sprintf(template_start, col_name))
  print(df[[col_name]])
  cat(sprintf(template_end))
}
'''
  • 1
    Have you tried any of the suggestions at this question: https://stackoverflow.com/questions/36674824/use-loop-to-generate-section-of-text-in-rmarkdown . It seems like those methods for generating document sections on the fly should work. – MrFlick Aug 28 '23 at 16:05
  • @MrFlick: Appreciate the pointer. Got it working with your help and have updated the post with the solution – Kevin Sweeney Aug 29 '23 at 08:40

0 Answers0