Pepacz
Pepacz

Reputation: 959

Split code into several syntactically invalid chunks in R Knitr

Is it possible to get a nonformated markdown text inside a code chunk? My goal is to diplay a description inside a for cycle. In the example below, such operation leads to splitting the code into two syntactically invalid chunks:

I am using for cycle here
```{r results='hide'}
for(i in 1:5){
  foo()
```

There is a lot of interesting stuff inside
```{r results='hide'}
  bar()
}
```

which would ideally generate:

I am using for cycle here

for(i in 1:5){
  foo()

There is a lot of interesting stuff inside

  bar()
}

Upvotes: 1

Views: 495

Answers (1)

Kalin
Kalin

Reputation: 1761

Following advice from the comment by user2706569, you can define the code chunk once with a name and evaluate it. Then you can reuse the code chunk, but only echo the lines you want, and without evaluation.

Drawn from Yihui's examples...

The plots from the original evaluation are 
shown, but the code is not echoed here. (To 
omit all of the outputs, check out the 
chunk options such as `include=FALSE`.)

```{r mychunk, echo=FALSE}
## 'ugly' code that I do not want to show
par(mar = c(4, 4, 0.1, 0.1), cex.lab = 0.95, cex.axis = 0.9,
    mgp = c(2, 0.7, 0), tcl = -0.3)
plot(mtcars[, 1:2])
plot(mtcars[, 4:5])

```

Now describe the code as you wish without evaluation.

Here's the first and second lines from the original chunk.

```{r mychunk, echo=1:2, eval=FALSE}
```

Here's the third line.

```{r mychunk, echo=3, eval=FALSE}
```

Here's the fourth line.

```{r mychunk, echo=4, eval=FALSE}
```

Here's the fifth line.

```{r mychunk, echo=5, eval=FALSE}
```

Upvotes: 4

Related Questions