`r 2 + 2`Inline code and results
Inline code lets you execute an R expression directly within your narrative text, so a report always reflects the current data or computation, without manually copying results in.
Syntax for Inline Code
Inline code is written with a single pair of backticks, starting with the language identifier:
Do: Run this code inline where you are writing text in your own Quarto document.
See: including this in a sentence runs the code and prints only the result: 4.
Predict: now suppose a previous chunk already created an object, mean_score <- mean(c(5, 10, 15)). Before looking below, predict what the following inline code will show once rendered: the code itself, or the number it evaluates to?
`r mean_score`Explain: as predicted, only the result appears: “The average score is 10.” The expression is evaluated at render time, and only its result is shown; you can use any valid R expression, including objects created in earlier chunks.
Using Inline Code in Text
Inline code works well for numbers that should always match the current analysis. For example, the syntax
The mean mpg is `r round(mean(mtcars$mpg), 1)`.renders as: The mean mpg is 20.1. The same approach works for model results:
The regression slope is `r round(coef(lm(mpg ~ wt, data = mtcars))[2], 2)`.renders as: The regression slope is -5.34.
Raw inline results are often much longer or messier than you’d want in a sentence: an unrounded slope like -5.344471517... looks out of place in a report. Always round (round()) or format (format()) numeric results before embedding them, rather than leaving the raw computed value to print as-is.
Create a numeric vector called scores with a few values of your choice, then compute its mean rounded to 1 decimal place, the way you would for an inline result.
scores <- c(72.456, 88.219, 91.038, 65.774)
round(mean(scores), 1)[1] 79.4
If this were an inline expression in a report, e.g.
The average score is `r round(mean(scores), 1)`.it would render as: “The average score is 79.4.” Rounding keeps the embedded result readable in a sentence, rather than printing several unnecessary decimal places.