Jean
Golding
Institute
It is possible to make R repeat certain lines of code using loops. The ability to run a line of code multiple times is the first large step on your road to making your code more structured and reusable.
Imagine we have three strings in a vector that we want to print. We could start by calling cat
three times to create a program like:
loop.R
<- c("Jean", "Golding", "Institute")
my_words cat(my_words[1])
cat(my_words[2])
cat(my_words[3])
Jean
Golding
Institute
This printed the output we want. But you may feel that repeating the same call to cat
is wasteful code, particularly if we want to repeat the same operation for many elements. If we can manage to write that line only once then we could save ourselves some typing and potentially make the code easier to read!
FOR EACH word IN my_words
DO SOMETHING WITH word
We can write a for
loop in R which will perform a task once for each word in our vector:
loop.R
<- c("Jean", "Golding", "Institute")
my_words
for (word in my_words) {
cat(word, " ")
}
Jean Golding Institute
Even in this tiny example, we have ve taken a script that was four lines of code and have reduced it to three lines, and more interestingly the same loop will work no matter how many items there are in the vector my_words
.
This maps to real life where you may want, for example, to pay for each item on your shopping list. Another way of saying that could be “for each item on my shopping list, add its price to my total”, or as you would write that in R:
<- 0
total for (item in shopping_list) {
<- total + item
total }
If we want to write more code after the end of a loop, we have to make sure that we have closed the curly braces. So this code will print:
<- c("Hello", "R")
my_words
for (word in my_words) {
cat(word, " ")
}
Hello R
cat("Goodbye ")
Goodbye
On the contrary, the below code will print Goodbye
in each iteration. This is because it was inside the body of the loop.
<- c("Hello", "R")
my_words
for (word in my_words) {
cat(word, " ")
cat("Goodbye ")
}
Hello Goodbye R Goodbye
There’s a built in operator in R :
which provides you with numbers (integers) in a range. When given two numbers, e.g. 1:10
, it will give you integers, starting from the first one and going up (or down) to the number you gave in second place. We can use this directly into our loop as the object to loop over and it will print:
for (number in 1:10) {
cat(number, " ")
}
1 2 3 4 5 6 7 8 9 10
We can also loop over a range of numbers in descending order.
for (number in 5:-5) {
cat(number, " ")
}
5 4 3 2 1 0 -1 -2 -3 -4 -5