Programmatically create section heading with rmarkdown

Hi,

I would like to know if it is possible and what is the best way to programmatically create html section headings in a Rmarkdown code chuck. Specifically, I am trying to create section headings and plots dynamically within a loop. The example below illustrates a loop with 3 iterations, but in actuality, my code will exist in a Rmarkdown template which will process data of variable size and content so the number of iterations and headings is a priori unknown.

Thanks in advance for your help


title: "Untitled"
author: "Unknown"
date: "2024-10-17"
output: html_document

knitr::opts_chunk$set(echo = TRUE)

Intro

Hello world!

Analysis

required(ggplot2)
for (i in 1:3) {
  message( paste("Iteration", i) )
  ggplot(diamonds, aes(carat, price)) + geom_point()
}

If the problem is dynamically create html title/head by programming in Rmardkown, my approach could be used as reference.

  1. structure the rmd in three parts. they are html configuration, r setup code and html title.
  2. the example code

output:
html_document:
toc: yes
word_document: default
editor_options:
markdown:
wrap: 120

knitr::opts_chunk$set(echo = FALSE)
title <- paste0("the document name which can dynamically created here")

title: "r title"
author: "author name"
documentclass: ctexart
output:
word_document: default
html_document: default
rticles::ctex:
fig_caption: yes
number_sections: yes
toc: yes
classoption: "hyperref,"

that's all for dynamically create rmarkdown title in html format.

Pls vote if you like it.

WangYong

Thank you for your input.

Unfortunately, this does not address my initial question. I am trying to dynamically set the section titles within the html document, not the main document title.

Is this what you're looking for?

```{r}
#| results: asis

library(ggplot2)
for (i in 1:3) {
  cat("## Section heading ", i, "\n\n")
  print(ggplot(diamonds, aes(carat, price)) + geom_point())
  cat("\n\n")
}
```
1 Like

Thanks @arangaca,

I can't believe that the double line returns was the solution to this issue.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.