For-loops in R
In many programming languages, a for-loop is a way to iterate across a sequence of values, repeatedly running some code for each value in the list. In R, the general syntax of a for-loop is
for(var in sequence) {
code
}
where the variable var
successively takes on each value in sequence
. For each such value, the code represented by code
is run with var
having that value from the sequence.
Here, we show some simple examples of using a for-loop in R.
Printing a list of numbers
Let's say we wanted to print a list of numbers from 0 to 3, inclusive. In R, the command 0:3
will create a vector with the numbers from 0 to 3, as you can see by entering that command at the R >
command prompt:
> 0:3
[1] 0 1 2 3
(At the beginning of the output, R prints a [1]
to let you know that lines starts with the first entry of the vector.)
We could create a simple for-loop that iterates through the four numbers of 0:3
and prints each number.
> for(var in 0:3)
{
print(var)
}
[1] 0
[1] 1
[1] 2
[1] 3
R outputs four lines, one for each number. (When typing the for-loop at the R >
command prompt, R adds a +
at the beginning of the line to indicate the command is continuing. We omit those +
signs for clarity.)
If you don't want R to print the [1]
at the beginning of the line, you could use the cat
(concatenate) command instead, but you need to explicitly add a newline character \n
to print each number on its own line.
> for(var in 0:3)
{
cat(var, "\n")
}
0
1
2
3
We could assign the vector of numbers to a variable and then reference the variable in the for-loop. It would work exactly the same way.
my_sequence = 0:3
> for(var in my_sequence)
{
cat(var, "\n")
}
0
1
2
3
Using for-loops with vectors
For-loops are especially convenient when working with vectors. Often we want to iterate over each element in a vector and do some computation with each element of the vector. We can also use for-loops to create or extend vectors, as R will automatically make a vector larger to accommodate values we assign to it.
First, lets create a vector using the c
(combine) command is illustrated in the page on vector creation.
> x = c(1,3,4,7)
> x
[1] 1 3 4 7
For any integer $i$ between 1 and 4, x[i]
denotes the $i$th element of the vector.
> x[1]
[1] 1
> x[2]
[1] 3
> x[3]
[1] 4
We can use a for-loop to add one to the first element of x
, add two to the second element of x
, etc. We let use the variable n
to store the number of elements in x
(i.e., 4). In the loop, we will use the variable i
to loop through the numbers 1, 2, 3, 4.
> n = length(x)
> for(i in 1:n)
{
x[i] = x[i] + i
}
> x
[1] 2 5 7 11
The for-loop is equivalent to running the four commands:
> x[1] = x[1] + 1
> x[2] = x[2] + 2
> x[3] = x[3] + 3
> x[4] = x[4] + 4
This for-loop creates a vector with five components where each component is double the previous.
> n = 4
a=1
> for(i in 1:n)
{
a[i+1] = 2*a[i]
}
> a
[1] 1 2 4 8 16