Chapter 8 Loops and Functions in R

In this chapter, we will delve into two fundamental concepts in R programming: loops and writing functions. Loops are a powerful tool for iterating over a sequence, making them essential for tasks that require repetitive operations. Writing functions, on the other hand, allows you to create reusable blocks of code, enhancing the efficiency and organization of your programming projects. By the end of this chapter, you will gain a solid understanding of how to effectively use for loops to automate repetitive tasks and how to write your own functions in R, thereby elevating your coding skills to a new level.

8.1 Loops

Repetition is a key component of programming. Loops enable you to execute the same piece of code multiple times, making data processing more efficient. If you have a previous programming experience in any language, these syntax should look familiar.

8.1.0.1 The for loop

The for loop in R is used to iterate over elements in a vector or list.

data <- c(1, 2, 3, 4, 5)
for (i in data) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

This will print numbers from 1 to 5. The loop iterates over each element in the vector c(1, 2, 3, 4, 5), setting the value to i and executing the code inside the loop.

8.1.0.2 The while loop

The while loop continues executing as long as a specified condition remains true.

count <- 1

while (count <= 5) {
  print(count)
  count <- count + 1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

In this example, the loop will keep printing and incrementing the value of counter until counter is no longer less than or equal to 5.

Be cautious with while loops: if the condition never becomes false, the loop will run indefinitely!

8.2 Writing custom functions in R

Functions form the backbone of most programming languages, and R is no exception. While R provides a rich library of built-in functions, there are times when you’ll need to define your own. Custom functions in R allow you to encapsulate a series of commands into a single reusable unit.

Why write custom functions?

  • Reusability: Once you’ve written and tested a function, you can use it repeatedly without having to retype or copy-paste the same lines of code.
  • Maintainability: Changes can be made in one place (inside the function) rather than at multiple locations where the code might be used.
  • Clarity: Well-named functions can make your main code more readable, as they abstract away the complexity.

8.2.0.1 Simple example

add_two <- function(a, b) {
  # Add a and b and return the value
  added <- a + b
  return(added)
}
  • add_two is the custom name of the function.
  • a and b are the inputs to the function. You can name them x and y, or anything else, as long as they are kept consistent throughout the function definition. You can also change the number of inputs for your function.
  • The return statement specifies the output of your function. If omitted, the function will return the result of the last expression evaluated.

You can run this function with various choices of a and b:

add_two(1, 3)
## [1] 4
add_two(20, 35.5)
## [1] 55.5

At this time, we shall keep it simple. You will eventually see more complex usages of custom functions.

8.3 Further reading

This chapter has been intentionally succinct. We’ve omitted several other aspects of programming in R such as for loops, and other aspects of iterative programming. To get a better sense of programming in R and to learn more, please see the following links: