3

I am using RStudio. I want to generate headers and plots inside a for loop. But it does not work.

My code should generate three headers. One for each region_value. But I only obtain the header for the first region value.

What is wrong in my code?

---
title: "Generate Headers"
format: html
editor: visual
---

## Generate dataframe

```{r}
#| echo: false
#| warning: false

library(tidyverse)
region = c(replicate(100,"A"),replicate(100,"B"),replicate(100,"C"))
variable = c(replicate(50,"var_a"),replicate(50,"var_b"),replicate(50,"var_a"),replicate(50,"var_b"),replicate(50,"var_a"),replicate(50,"var_b"))
value = runif(300, min = 0, max = 100)
df = data.frame(region = region, variable = variable, value = value)
```

# Plots

```{r}
#| echo: false
#| results: asis

regions_values <- unique(df$region)
for (region_value in regions_values){
  cat("## ", region_value, "\n")
  dfplot <- df |> filter(region == region_value)
  p <- ggplot(dfplot, aes(x=variable, y=value)) + geom_boxplot() 
  print(p)
  cat("\n")
  
}

```

1 Answer 1

5

In markdown you need a new line before your ## line for it to be interpreted as a header. As the syntax section of the Markdown Guide says,

You should also put blank lines before and after a heading for compatibility.

Change the second block to:

#| echo: false
#| results: asis

regions_values <- unique(df$region)
for (region_value in regions_values){
  cat("## ", region_value, "\n")
  dfplot <- df |> filter(region == region_value)
  p <- ggplot(dfplot, aes(x=variable, y=value)) + geom_boxplot() 
  print(p)
  cat("\n\n")
}

This will produce three headers:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.