Problems with including R chunks in post

For a post I'm writing, I would like to include a part of an R Markdown document which includes a code chunk. It's very important that the last ``` in the code chunk is visualized. What's the right way to do that? If I write:

**my Rmarkdown doc**
Here's a chunk:

```{r chunky_chunk}
getwd()

as you can see, the last "````" is not shown. If I try to block-quote, not even the first ``` is printed:

my Rmarkdown doc
Here's a chunk:

getwd()

How can I solve this?

1 Like

Prefix your backticks with the escape character \ if you're trying to show the literal text
```{r chunky_chunk}
getwd()
```

1 Like

The easiest way I've found is to enclose the chunk in 4 backticks, so this:

 ````
 **my Rmarkdown doc**
 Here's a chunk:
 
 ```{r chunky_chunk}
 getwd()
 ```
 ````

Becomes this:

**my Rmarkdown doc**
Here's a chunk:

```{r chunky_chunk}
getwd()
```

That way, you can still use code formatting. The other option is to indent everything by 4 spaces (like on Stack Overflow), but the lack of a button to do that makes it more annoying. Also, you'll see that the parser doesn't handle unbalanced quotes, like the ones that tend to show up in contractions.

I feel like this should be a sticky in the #shiny and #R-Markdown categories. We get some scary looking posts there.

4 Likes

@nick niiiice! @mara, sorry if I'm changing my chosen solution but I like @nick's solution a lot. I will impress it in my mind :slight_smile:

This recent blog post about verbatim code chunk could help you have an overview of possible solutions

2 Likes

I think it should be super obvious how to include nicely formatted code in posts. Some questions are just plain pain to read. Maybe renaming a button called Pre-formatted text to something like Include R chunk or Code would help?

1 Like