3.10 Programming in R

3.10.1 Writing Scripts

An R script is a file containing a sequence of R commands that can be executed together. Scripts make your work reproducible and shareable. In RStudio, create a new script via File -> New File -> R Script.

# Example R script
# This script calculates the square of a number

# Define a function to calculate the square
square <- function(x) {
  return(x^2)
}

# Perform calculations
number <- 5
result <- square(number)
print(result)
## [1] 25

3.10.2 Loops

Loops execute a block of code repeatedly. The for loop iterates over a sequence; R also supports while and repeat loops.

# Example of a for loop
for (i in 1:5) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

3.10.3 Conditional Statements

The if-else statement lets your code make decisions based on conditions.

# Example of an if-else statement
x <- 10
if (x > 5) {
  print("x is greater than 5")
} else {
  print("x is less than or equal to 5")
}
## [1] "x is greater than 5"

3.10.4 Writing Functions

You can define your own functions to encapsulate reusable logic. Functions take arguments, perform operations, and return results.

# Example of a function
calculate_average <- function(x, y) {
  avg <- (x + y) / 2
  return(avg)
}

# Call the function
result <- calculate_average(5, 7)
print(result)
## [1] 6

3.10.5 The Pipe Operator

R’s native pipe operator, |>, passes the result of one expression as the first argument to the next function. This allows you to chain operations together in a readable, left-to-right sequence instead of nesting function calls.

# Without the pipe: nested and hard to read
round(mean(mtcars$mpg), 2)
## [1] 20.09
# With the pipe: reads left to right
mtcars$mpg |> mean() |> round(2)
## [1] 20.09

Both lines produce the same result, but the piped version reads as a sequence of steps: “take the mpg column, then compute the mean, then round to 2 decimal places.” This becomes especially valuable in data manipulation, where you might chain five or more operations together. We will use the |> pipe extensively starting in Chapter 5.

Note: Older R code and some packages use %>% (from the magrittr package) instead of |>. They work similarly, but this textbook uses the native pipe |>, which is built into R 4.1 and later and requires no additional packages.