`r 2 + 2`Inline code and results
In Quarto, inline code allows you to execute R expressions (or code in other supported languages) directly within your narrative text. This makes it possible to embed calculated results dynamically into your report, so your text always reflects the latest data or computations. Inline code is particularly useful for reporting summary statistics, model results, or dates without manually updating the text.
Syntax for Inline Code
Inline R code in Quarto is enclosed with single backticks and starts with the language identifier, followed by the expression:
Including such a statement in text directly runs the code and prints the result: 4.
Similarly, you can embed variables defined in previous code chunks:
mean_score <- mean(c(5, 10, 15))
mean_score[1] 10If we now include in a sentence
`r mean_score`This immediately prints the value of mean_score: The average score is 10.
Key points:
- The expression inside the inline code is evaluated at render time.
- You can use any valid R expression, including functions, arithmetic, or objects created in previous chunks.
- Inline code only outputs the result, not the code itself.
Using Inline Code in Text
Inline code can be used in:
- Numerical results:
The dataset contains `r nrow(mtcars)` rows and `r ncol(mtcars)` columns.The dataset contains 32 rows and 11 columns.
- Statistical summaries:
The mean mpg is `r round(mean(mtcars$mpg), 1)`.The mean mpg is 20.1.
- Dynamic dates or times:
Report generated on `r Sys.Date()`.Report generated on 2025-10-20.
- Model results:
The regression slope is `r coef(lm(mpg ~ wt, data = mtcars))[2]`.The regression slope is -5.3444716.
These ensure your narrative text always reflects the current state of your analysis.
Best Practices
- Keep expressions simple: Inline code should be concise; longer computations belong in code chunks.
- Name variables clearly: Use descriptive names in code chunks so inline references are readable.
- Round or format results: Inline outputs may need rounding (round()) or formatting (format()) for clarity.
Inline code is a key feature for reproducible reporting, as it reduces manual copying of results and ensures that text and code remain synchronized. By combining inline expressions with code chunks, you can create documents that automatically update whenever your data or analysis changes.