1

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()
}
Pepacz
  • 881
  • 3
  • 9
  • 24
  • 1
    Spoof it. Put your syntactically complete code chunk with `echo = F`, then break up your code however you want with `eval = F`. – Gregor Thomas Dec 14 '15 at 19:17
  • @Gregor : I want my code to be evaluated. – Pepacz Dec 14 '15 at 19:40
  • 2
    Right, but you can only evaluate syntactically valid code. So the first one that you **do** evaluate has all your code and is syntactically valid, but has `echo = F` so it won't be displayed. Then you can display the code however you want, in as many chunks as you want, with `eval = F`. And it won't matter if you break up a for loop across chunks because no evaluation means no syntax error. – Gregor Thomas Dec 14 '15 at 19:56
  • ok, now I get it. Well, this will perhaps work, but I need to have the code there twice. But thanks anyway. – Pepacz Dec 14 '15 at 20:50
  • Related (but definitely not duplicate), could that method work? http://stackoverflow.com/questions/26819258/format-text-inside-r-code-chunk – Mörre Dec 15 '15 at 14:00
  • 2
    Do you mean something like the feature described in the section [Advanced usage of the echo option](http://yihui.name/knitr/demo/output/)? Not sure if I get the question because you write that you want to split a chunk into pieces, but then you show different codes (and not code that is a subset of other code). – CL. Dec 15 '15 at 15:51

1 Answers1

4

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}
```
Kalin
  • 1,691
  • 2
  • 16
  • 22