rr-markdownrstudioknitrquarto

Generate paragraphs inside a loop in Quarto


I want to generate with R / Quarto a Word document (docx) in which, inside an item, I have sub-items created by looping. I’m using R version 4.2.2, R Studio 2022.12.0 Build 353, Quarto 1.2.280 and Ubuntu 20.04.

For example, after an introductory text given an overview on a topic, I want to produce sub-items with details of each item.

Without a looping the code would be:

---
title: "Data by County"
format:
  docx:
    number-sections: true
---

```{r}
#| echo=FALSE,
#| include=FALSE

dat.county <- data.frame(
  county = LETTERS[1:5],
  pop_num = round(runif(5,100,500)),
  gdp = runif(5,1000,5000)
)
```

# Identifying county characteristics

A total of `r nrow(dat.county)` counties, with a total population of `r sum(dat.county$pop_num)` thousand people were characterized as follows:

## County `r dat.county[1,1]`

County `r dat.county[1,1]` has a population of `r dat.county[1,2]` thousand people with a real gross domestic product of `r dat.county[1,3]`.

## County `r dat.county[2,1]`

County `r dat.county[2,1]` has a population of `r dat.county[2,2]` thousand people with a real gross domestic product of `r dat.county[2,3]`.

and so on.

I tried to insert a looping like the one below, but it didn't work. "##" are not recognized as a header. Also I had problems with line breaks ans paragraphs. Finally, the code using cat is not as elegant as the text above.

```{r}
#| echo=FALSE

  for (i in 1:nrow(dat.county)) {
  
  cat("## County",dat.county[i,1],"\n")
  
  cat("County ",dat.county[i,1]," has a population of ",dat.county[i,2]," thousand people with a real gross domestic product of ",dat.county[i,3],"\n")
  }
```

My question is, how can I generate some thing like

## County `r dat.county[i,1]`

County `r dat.county[i,1]` has a population of `r dat.county[i,2]` thousand people with a real gross domestic product of `r dat.county[i,3]`

inside a looping?


Solution

  • You just need to add the chunk option results:'asis' and use a double newline when calling cat():

    ---
    title: "Data by County"
    format:
      docx:
        number-sections: true
    ---
    
    
    ```{r}
    #| echo: false
    #| include: false
    
    dat.county <- data.frame(
      county = LETTERS[1:5],
      pop_num = round(runif(5,100,500)),
      gdp = runif(5,1000,5000)
    )
    ```
    
    ```{r}
    #| echo: false
    #| results: 'asis'
    
      for (i in 1:nrow(dat.county)) {
      
      cat("## County",dat.county[i,1],"\n\n")
      
      cat("County ",dat.county[i,1]," has a population of ",dat.county[i,2]," thousand people with a real gross domestic product of ",dat.county[i,3],"\n\n")
      }
    ```
    

    Gives:

    enter image description here