8

I have such a list:

> lSlopes
$A
  Estimate 2.5 % 97.5 %
1     2.12 -0.56   4.80

$B
  Estimate 2.5 % 97.5 %
1     2.21 -0.68   5.10

$C
  Estimate 2.5 % 97.5 %
1     2.22 -2.21   6.65

It has three elements but its length can change (according to the data not shown here). I want to display each element in a chunk.

My first idea was to write a chunk containing a loop calling knit_child() at each step, but I don't know how to get the correct rendering with knit_child().

I have find the following solution which works well but which requires two Rmd files; the first one calls the second one and the second one recursively calls itself:

mainfile.Rmd:

```{r, echo=FALSE}
J <- length(lSlopes)
i <- 1
```

```{r child, child="stepfile.Rmd"}
```
Nice!

stepfile.Rmd:

```{r, echo=FALSE}
lSlopes[[i]]
i <- i+1
```

```{r child, child="stepfile.Rmd", eval= i <= J}
```

This exactly generates the rendering I want:

enter image description here

I love this tricky solution but I wonder whether there exists a non-recursive solution ?

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • By the way there's a problem with this solution if one wants to include some inline R code: https://github.com/yihui/knitr/issues/613 – Stéphane Laurent Sep 29 '13 at 19:38
  • 1
    Plenty of examples at https://github.com/yihui/knitr-examples: 020, 069, 075, ... Please feel free to answer your own question after you learn these examples. – Yihui Xie Sep 30 '13 at 02:14
  • @Yihui, I don't understand why there is the option `include` in the code given in my answer ? There's something strange: actually I knit these files from a Shiny app, and the code produces an unexpected folder with a figure. – Stéphane Laurent Oct 03 '13 at 13:38
  • @Yihui Ah ok, I have removed `include=FALSE` and I understand this point. But the folder with the figure is very strange... I'll try to isolate the problem and to post it elsewhere. – Stéphane Laurent Oct 03 '13 at 13:44
  • @Yihui I think the strange folder was a consequence that I didn't generate the output in the current directory. – Stéphane Laurent Nov 12 '13 at 14:26

1 Answers1

7

Below is the RMarkdown solution analogous to https://github.com/yihui/knitr-examples/blob/master/020-for-loop.Rnw, using knit_child(). As my solution, it requires two files, but it is much more clear.

mainfile.Rmd:

```{r, echo=FALSE}
J <- length(lSlopes)
```

```{r runall, include=FALSE}
out <- NULL
for (i in 1:J) {
  out <- c(out, knit_child('stepfile.Rmd'))
}
```

`r paste(out, collapse = '\n')` 

Nice!

stepfile.Rmd:

```{r, echo=FALSE}
lSlopes[[i]]
```
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225