1

Say I have the following code in knitr. How can I run it multiple times with different values of i?

```{r, echo=FALSE}
i<-0.1
```

### X,Y plot of Y=X+e where e is a standard normal distro: mean=0, sd=`r i`

```{r, echo=FALSE}
r<-rnorm(100,mean=0,sd=i)
x<-seq(0,1,length.out=100)
y<-x+r
plot(x,y)
```

EDIT:

As has been suggested ... I tried to do something like this: start a loop in an R code block, have a template in between and then close the loop -- R throws and error.

```{r, echo=FALSE}
for (i in 1:4) {
```

# bla 

```{r, echo=FALSE}
}
```
user1172468
  • 5,306
  • 6
  • 35
  • 62
  • You could [reuse](http://stackoverflow.com/questions/11080793/reusing-chunks-that-include-plotting-with-knitr-rmd) the chunk, but why don't you just loop over these 4 lines of codes multiple times? – CL. Mar 30 '17 at 09:54
  • precisely ... how do I loop over the heading -- that was kinda my question -- – user1172468 Mar 30 '17 at 17:50
  • Sorry, I didn't get the point initially. I thought `### X,Y plot ...` was meant as R comment and missed that it's a markdown heading. Context matters … See my answer (soon). – CL. Mar 30 '17 at 19:22
  • @CL, many thanks -- looking forward to it – user1172468 Mar 30 '17 at 19:24

1 Answers1

2

What makes this question tricky is that not only the chunk content (the plot) must be repeated, but the heading as well. That's why we can neither simply reuse the chunk nor just loop over the plot command like

for (i in 1:3) { plot(rnorm(100, sd = i)) }

But it's almost that simple: We loop over the code that produces the plot and output the heading from inside the loop. This requires the chunk option results="asis" and cat to get verbatim markdown output:

```{r, echo=FALSE, results = "asis"}
sdVec <- c(0.1, 0.2, 0.3)
for (sd in sdVec) {
  cat(sprintf("\n### X,Y plot of Y=X+e where e ~ N(0, %s)", sd))
  r<-rnorm(100,mean=0,sd=sd)
  x<-seq(0,1,length.out=100)
  y<-x+r
  plot(x,y)
}
```

See this answer for related issues.

Community
  • 1
  • 1
CL.
  • 14,577
  • 5
  • 46
  • 73