36  Writing Functions in Methods and Results

How to use R functions and inline code to embed statistics in text

Author

Zihan Hei

Published

10.15.2025

Abstract

This chapter teaches researchers to write reproducible results sections by computing statistics in R and embedding them directly into report text. Students learn a two-step process: (1) calculate statistics using R functions and store them as objects, and (2) insert those values into prose using Quarto’s inline code syntax. Through five practical examples, the chapter covers calculating sample sizes, computing percentages, formatting numbers as words, creating descriptive statistics tables, and running statistical tests. By replacing manually typed numbers with code-generated values, researchers eliminate transcription errors and create reports that automatically update when data or analyses change, following reproducible research best practices. By the end of this chapter, researchers will be able to transform static numbers in their research papers into dynamic, code-generated values for research reproducibility.

Keywords

quarto publishing, in line coding, writing

Open Project → Open .qmd → Run load-library chunk → Run All Chunks Above → code. If anything looks wrong, use Ref’s Quick Checklist.

ImportantImportant: Advanced module (not required)

This is an advanced chapter and not required for your report!

In reproducible research, writing numbers manually (e.g., “We surveyed 120 people.”) can lead to errors if you import data later (after you have collected 140 people). Instead, use R functions inside Quarto to turn your results directly into sentences!

36.1 Load Library

## need to run chunks with both regular r and webr-r versions for this page to work
#| label: setup-regular-r
#| include: false
#| message: false
#| warning: false

# Load packages for regular R chunks
library(dplyr)
library(tidyr)
library(psych)
library(tibble)
library(knitr)
library(scales)
library(english)
library(stringr)

healthbeliefsdata <- read.csv("data/healthbeliefs_SELECT.csv")   # the same 122-row subset, as a file

36.2 Example Dataset

The example dataset, healthbeliefs_SELECT.csv (122 people, 44 variables), is a small subset of a larger dataset collected via Prolific on March 15, 2025. It is in the playbook’s data folder, and the code cell below fetches it so that the cells on this page can run in your browser. For more information, review the read me file.

36.3 Inline R Code

The traditional process of writing a results section of a research paper usually involves three steps: 1) running the analyses, 2) copying statistics and p-values from the data analysis software into a word document, and 3) writing text to interpret the results. In each of these steps, researchers can make an error. Using inline R code eliminates step2 of copying-and-pasting of numbers into a report or manuscript and reduces parts of step 3. Below are a few examples of how to use inline R code to generate numbers or text using functions:

  1. Report Sample Size

  2. Report Numbers and Percentages

  3. Write Numbers as Words

  4. Report Descriptive Stats in a Table

  5. Report a Parameter and p-value

36.4 Example 1: Report Sample Size

36.4.1 create object: total_responses

36.5 use in line code

In your report, write like this:

We surveyed a total of `r total_responses` participants.

When you render the output, you’ll get:

We surveyed a total of 122 participants.

36.6 Example 2: Report Numbers and Percentages

You can combine counts and percentages easily.

36.6.1 create an object for the sum of each racial identity in the sample

36.6.2 use inline r code with total_responses

In your report, write like this:

Out of `r total_responses` participants, The final sample was roughly balanced in terms of 
racial identity (White: `r percent(white, accuracy = 0.1)`, 
                 Black: `r percent(black, accuracy = 0.1)`,
                 Asian: `r percent(asian, accuracy = 0.1)`, 
                 Mixed/Other: `r percent(mixed_other, accuracy = 0.1)`).

When you render the output, you’ll get:

Out of 122 participants, The final sample was roughly balanced in terms of racial identity
(White: 40.2%, Black: 23.0%, Asian: 18.9%, Mixed/Other: 18.0%).

36.7 Example 3: Write Numbers as Words

36.7.1 load library

36.7.2 report numbers as words

In your report, write like this:

A total of `r str_to_title(as.character(english(total_responses)))` participants were included in the analysis.

When you render the output, you’ll get:

A total of One Hundred And Twenty-Two participants were included in the analysis.

36.8 Example 4: Report descriptive statistics in a table a table by using inline R code (Mean, SD, Range)

Writing functions can help researchers output the mean, median, sd, min, max and output these descriptive statistics into a table.

36.8.1 create variables

# Define Continuous Variables
continuous_vars <- c("AGE", "SOCIALSTATUS", "POLITICALBELIEFS", paste0("ZEROSUM_", 1:11)
)

desc_table_continuous <- healthbeliefsdata |>
  select(all_of(continuous_vars)) |>
  psych::describe() |>
  tibble::rownames_to_column(var = "Variable") |>
  select(Variable, n, mean, median, sd, min, max)

# Create table
knitr::kable(desc_table_continuous, digits = 2)
Descriptive Stats Table for Continuous Variables
Variable n mean median sd min max
AGE 121 36.10 33.0 12.73 19 73
SOCIALSTATUS 122 5.30 5.5 1.78 1 9
POLITICALBELIEFS 120 3.67 4.0 1.35 1 6
ZEROSUM_1 122 3.92 4.0 1.78 1 7
ZEROSUM_2 121 4.75 5.0 1.59 1 7
ZEROSUM_3 121 4.92 5.0 1.49 1 7
ZEROSUM_4 121 3.07 3.0 1.69 1 7
ZEROSUM_5 122 2.84 3.0 1.75 1 7
ZEROSUM_6 121 3.43 3.0 2.07 1 7
ZEROSUM_7 120 3.52 4.0 1.81 1 7
ZEROSUM_8 121 2.93 3.0 1.63 1 7
ZEROSUM_9 121 2.59 2.0 1.74 1 7
ZEROSUM_10 122 3.20 3.0 1.75 1 7
ZEROSUM_11 121 3.17 3.0 1.74 1 7

36.8.2 create table

In your report, write like this:

Descriptive statistics for all study variables are presented in Continuous Descriptive Statistics Table. 
The sample consisted of `r nrow(healthbeliefsdata)` participants, 
with a mean age of `r round(desc_table_continuous$mean[desc_table_continuous$Variable == "AGE"], 2)` 
years (SD = `r round(desc_table_continuous$sd[desc_table_continuous$Variable == "AGE"], 2)`, 
range = `r desc_table_continuous$min[desc_table_continuous$Variable == "AGE"]`
– `r desc_table_continuous$max[desc_table_continuous$Variable == "AGE"]`). 

Participants reported a mean social status of 
`r round(desc_table_continuous$mean[desc_table_continuous$Variable == "SOCIALSTATUS"], 2)` 
(SD = `r round(desc_table_continuous$sd[desc_table_continuous$Variable == "SOCIALSTATUS"], 2)`) on a 10-point scale.

When you render the output, you’ll get:

Descriptive statistics for all study variables are presented in Continuous Descriptive Statistics Table. 
The sample consisted of 122 participants, with a mean age of 36.1 years (SD = 12.73, range = 19 – 73). 
Participants reported a mean social status of 5.3 (SD = 1.78) on a 10-point scale.

36.9 Example 5: Report a parameter and p-values

Inline R code is used to report the parameter and p-value of a Kruskal-Wallis Test.

36.9.1 run analyses

36.9.2 include inline R code with reporting

In your report, write like this:

There was no significant difference in ZEROSUM_1 scores across political party groups, 
Kruskal-Wallis χ²(`r kw.ZEROSUM_1.party$parameter`) = `r round(kw.ZEROSUM_1.party$statistic, 2)`, 
*p* = `r signif(kw.ZEROSUM_1.party$p.value, 3)`.

When you render the output, you’ll get:

There was no significant difference in ZEROSUM_1 scores across political party groups, 
Kruskal-Wallis χ²(2) = 1.5, p = 0.473.

36.10 Common Pitfalls to Avoid

  • Object not found errors - Make sure you create objects, such as total_responses, before using functions, such as percent(), before referencing them inline
  • Wrong variable names - R is case-sensitive: age ≠ AGE
  • Missing packages - Load scales and english if outputting english text

Save → Render → Back up to ELN → Quit, Don’t Save workspace. Details: Ref’s Quick Checklist.