In this tutorial we will have a look at how you can write a basic for loop in R. It is aimed at beginners, and if you’re not yet familiar with the basic syntax of the R language we recommend you to first have a look at this introductory R tutorial.
Conceptually, a loop is a way to repeat a sequence of instructions under certain conditions. They allow you to automate parts of your code that are in need of repetition. Sounds weird? No worries, it will become more clear once we start working with some examples below.
Before you dive into writing loops in R, there is one important thing you should know. When surfing on the web you’ll often read that one should avoid making use of loops in R. Why? Well, that’s because R supports vectorization. Simply put, this allows for much faster calculations. For example, solutions that make use of loops are less efficient than vectorized solutions that make use of apply functions, such as lapply and sapply. It’s often better to use the latter. Nevertheless, as a beginner in R, it is good to have a basic understanding of loops and how to write them. If you want to learn more on the concepts of vectorization in R, this is a good read.
Writing a simple for loop in R
Let’s get back to the conceptual meaning of a loop. Suppose you want to do several printouts of the following form: The year is [year] where [year] is equal to 2010, 2011, up to 2015. You can do this as follows: