Volker Holzendorf
Volker Holzendorf

Reputation: 247

R Markdown: loop with child.rmd

Hei,

I'm have to document a database. Therefor I want to document database schemes within a R markdown file. The database schemes to be documented are linked together.

I wrote some functions to do the job.

Now , the only thing I have to do, is to define the databese schemes. This is a simple vector of strings.

In my R Markdown file I use child markdown files as well.

Question:

Is it possible to loop for each element of the vector of strings and calling child.rmd?

My {mother.rmd}:

---
title: "R Markdown: Loop with child.rmd"
output:
  html_document:
    df_print: paged
---

```{r}
txtvec <- c("first","second","third")
```

# Is it possible to loop this?

```{r}
i <- 1
```
```{r child="child.rmd"}
```

```{r}
i <- 2
```
```{r child="child.rmd"}
```

```{r}
i <- 3
```
```{r child="child.rmd"}
```

My {child.rmd} - in reality much more complicated, with text and r-chunks

## `r txtvec[i]` 

Some more text...

Thank you for your answers!

Upvotes: 2

Views: 1084

Answers (1)

Marius Barth
Marius Barth

Reputation: 646

I think including the following code chunk will do what you are looking for:

    ```{r results='asis'}
    txtvec <- c("first","second","third")
    res <- vector(mode = "list", length = 3L)
    for (i in 1:3) {
      res[[i]] <- knitr::knit_child("child.rmd", quiet = TRUE, envir = environment())
    }

    cat(unlist(res), sep = '\n')
    ```

Note that within the child document, (as far as I understand) you have to remove all chunk labels, because these would otherwise be duplicated. My answer is based on the following piece of documentation that may be helpful, too: https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html

Upvotes: 4

Related Questions