Problems with including R chunks in post


#1

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?


#2

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


#3

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

@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:


#5

This recent blog post about verbatim code chunk could help you have an overview of possible solutions
https://yihui.name/en/2017/11/knitr-verbatim-code-chunk/


#6

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?