Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape an RMarkdown chunk?

Tags:

r-markdown

I am trying to render the syntax for chunks of code in RMarkdown to a pdf. The final output should look like

```{r}
#some code
```

Rather than just

#some code
like image 839
Dambo Avatar asked Aug 12 '17 19:08

Dambo


People also ask

How do you not run a chunk in R Markdown?

If you don't want any code chunks to run you can add eval = FALSE in your setup chunk with knitr::opts_chunk$set() . If you want only some chunks to run you can add eval = FALSE to only the chunk headers of those you don't want to run.

How do you escape in R Markdown?

The way to escape a special character is to add a backslash before it, e.g., I do not want \_italic text\_ here . Similarly, if # does not indicate a section heading, you may write \# This is not a heading . As mentioned in Section 4.12, a sequence of whitespaces will be rendered as a single regular space.

How do I stop R from running a chunk?

The shortcut to interrupt a running process in R depends on the R software and the operating system you are using. However, if you are using RStudio on a Windows computer, you can usually use Esc to stop a currently executing R script. Then, we can press Esc to interrupt the loop.

How do I stop knitting in R?

In these situations, we could consider using the knit_exit() function in a code chunk, which will end the knitting process after that chunk. Normally you have to wait for 100 seconds, but since we have called knit_exit() , the rest of the document will be ignored.


1 Answers

The best options to answer this can be found on the RStudio website. See the article on getting verbatim R chunks into rmarkdown http://rmarkdown.rstudio.com/articles_verbatim.html

My preferred solution is to add an inline R code at the end of the first line to make the chunk appear correctly in the output like so:

```{r eval=TRUE}` r ''`
seq(1, 10)
```

Which produces

```{r eval=TRUE}
seq(1:10)
```

Rather than

##  [1]  1  2  3  4  5  6  7  8  9 10

Another way to do the same thing is treat the code chunk as a string (I don't usually use the -> operator but in this case I think this improves readability):

```{r comment = ""}
"{r eval=TRUE}
seq(1, 10)
" -> my_code_string

cat("```", my_code_string, "```", sep = "")
```

Which outputs:

```{r eval=TRUE}
seq(1, 10)
``` 

This question is also a possible duplicate of How to embed and escape R Markdown code in a R Markdown document

like image 75
markdly Avatar answered Sep 17 '22 15:09

markdly