3 min read

Adding R code to R Markdown posts

View raw source for this post

Obviously, one of the main benefits of the blogdown package for R users is to be able to include R code in posts. To add R code, make sure that you start by creating a new R Markdown post (as opposed to a markdown post). You can do this one of two ways, either in the console:

blogdown::new_post(rmd = TRUE) # false is the default!

Or using the “new post” addin within RStudio, as described in the blogdown book.

As in R Markdown/knitr documents, you can include two types of R code: R code chunks, and inline R code.

Example 1: Adding R code chunks

Adding an R code chunk works just like in an R Markdown document: you can use the Add Chunk command in the RStudio editor toolbar or type the chunk delimiters ```{r} and ```. To add your R code to the chunk, insert it between the two series of backticks. You may also add chunk labels and options within the braces, separated by commas.

```{r chunk-label, echo = FALSE, fig.cap = 'A figure caption.'}
1 + 1
rnorm(10)  # 10 random numbers
plot(dist ~ speed, cars)  # a scatterplot

To learn more about knitr chunk options, see the web page http://yihui.name/knitr/options. Also see the R Markdown Reference Guide for a complete list of knitr chunk options.

Additionally, as with R Markdown documents, you can set global options that will apply to every chunk in your post:

```{r setup, include = FALSE}
knitr::opts_chunk$set(tidy = FALSE, echo = FALSE)

Note that it is not recommended to change the knitr chunk options fig.path or cache.path in R Markdown. The default values of these options work best with blogdown. Please read Section D.5 in the blogdown book to know the technical reasons if you prefer.

Example 2: Adding inline R code

To add inline R code, enclose the code between two backticks, with an “r” and a space placed before the actual code: `r R_CODE`. So for example, `r sum(1:5)` would render as the number 15 in text. When using inline code, the results of the code will always be displayed (never the code), and the text formatting in your post will be applied to the results. Thus, typing 15 looks the same as the R output 15 when rendered.


If you are an R Markdown user, be careful to avoid knitting your file to html. Do serve your site (again, using either the console or RStudio addin), as this function generates the html file that will be viewable on your site. LiveReload is implemented via blogdown::serve_site(), so if that function is running, your website (including all the posts) will be automatically rebuilt and reloaded in your web browser as soon as you edit and save your R Markdown post.