Inline R Code in RMarkdown

What is inline R code and why should we use it?

Inline R code is just another way of including R code in an RMarkdown document, such that it gets evaluated when it gets compiled (or “knitted”). As well as including R code in a code-chunk:

```{r setup, include = FALSE}

mean(mydata$outcome_variable)
```

We can include little bits of R code in our text, to integrate it full with our written report:

The mean of my outcome variable was `r mean(mydata$outcome_variable)`, with a standard deviation of `r sd(mydata$outcome_variable)`.

This is really useful, because it means that if you update your analysis (for instance you discover you have to exclude a number of participants) then you don’t have to edit your paragraphs - they will update automatically!

Example

Writing like this

library(tidyverse)
pass_scores <- read.csv("https://edin.ac/2wJgYwL") 
res2 <- t.test(pass_scores$PASS, mu = 33, alternative = "less")

A one-sided one-sample t-test was conducted in order to determine if the average score on the Procrastination Assessment Scale for Students (PASS) for a sample of `r nrow(pass_scores)` students at Edinburgh University was significantly lower ($\alpha = .05$) than the average score obtained during development of the PASS.

Edinburgh University students scored lower (Mean = `r mean(pass_scores$PASS) %>% round(2)`, SD = `r sd(pass_scores$PASS) %>% round(2)`) than the score reported by the authors of the PASS (Mean = 33). This difference was statistically significant (t(`r nrow(pass_scores)-1`) = `r res2$statistic %>% round(2)`, p < .05, one-tailed).

Compiles to look like this!

A one-sided one-sample t-test was conducted in order to determine if the average score on the Procrastination Assessment Scale for Students (PASS) for a sample of 20 students at Edinburgh University was significantly lower (\(\alpha = .05\)) than the average score obtained during development of the PASS.

Edinburgh University students scored lower (Mean = 30.7, SD = 3.31) than the score reported by the authors of the PASS (Mean = 33). This difference was statistically significant (t(19)=-3.11, p < .05, one-tailed).

In the example above:

Tips for writing inline code

To make it easier when writing, it helps to try and keep inline R code a succinct as possible. It is therefore useful to use a code-chunk to store your results in a named object, and then refer to that object in the inline R code. Something which was not done in the above example, would be to round the numbers to the relevant decimal places in the object, rather than in the inline R code.