Nick logo Credibly Curious

Nick Tierney's (mostly) rstats blog

Just Quickly: How to show verbatim inline R code

2019/07/10

Categories: rstats rmarkdown teaching

I’ve recently asked on the Rstudio community page how to make code chunks appear verbatim.

Not sure what I mean by this?

Well, showing your entire code chunk is something taht comes up when you are teaching people about rmarkdown. One of the issues is that you want to show people what an rmarkdown code chunk looks like - not just echo the output.

For example, here is an rmarkdown code chunk:

library(ggplot2)
ggplot(airquality,
       aes(x = Ozone,
           y = Solar.R)) + 
  geom_point()

Hooray, code, and a plot!

But…you can’t see that I have set two chunk options so that no warning message is given - warning = FALSE, message = FALSE.

So, how do you show your code chunk, like, the whole thing, verbatim?

You could instead demo everything on your computer, or show a screenshot, but that just isn’t practical, or scalable, and kind of goes against the grain of rmarkdown and these ideas of literate programming.

Fortunately, there are some solutions to this problem, in the community link above, primarily linking Yihui’s blog post on this. For code chunks, Yihui demonstrates how I can show these code chunks - what I want to show is this:

```{r chunk-example, warning = FALSE, message = FALSE}
library(ggplot2)
ggplot(airquality,
       aes(x = Ozone,
           y = Solar.R)) + 
  geom_point()
```

Which, you can generate with code that looks like…well, I can’t actually seem to generate the code to show how you write that - I just get this:

````
```{r chunk-example, warning = FALSE, message = FALSE}
library(ggplot2)
ggplot(airquality,
       aes(x = Ozone,
           y = Solar.R)) + 
  geom_point()
```
````

But you can look into Yihui’s blog post for the details, or at the markdown source for my post here

So, how to do the same thing for inline code?

In any case, I came here to show yet another amazing feature of knitr that I did not know about until this morning. Just like you want to show the verbatim code code chunk, you can do the same thing with inline code.

Say I want to list the names of the month in text, say something like this:

The months of the year are January, February, March, April, May, June, July, August, September, October, November, December

You can show people the inline R code bit using the function knitr::inline_expr("month.name") in you inline expression:

The months of the year are `r month.name`

And if you want to see how I wrote that, I think the easiest way is to see what the markdown code here.

End

That’s it - use knitr::inline_expr("text") to show a verbatim inline expression in your code.