6.3 Looping for a fixed number of iterations

The for loop is used to execute repetitive code statements for a particular number of times. The general syntax is provided below where i is the counter and as i assumes each sequential value defined (1 through 100 in this example) the code in the body will be performed for that ith value.

For example, the following for loop iterates through each value (2010, 2011, …, 2016) and performs the paste and print functions inside the curly brackets.

If you want to perform the for loop but have the outputs combined into a vector or other data structure than you can initiate the output data structure prior to the for loop. For instance, if we want to have the previous outputs combined into a single vector x we can initiate x first and then append the for loop output to x.

However, an important lesson to learn is that R is not efficient at growing data objects. As a result, it is more efficient to create an empty data object and fill it with the for loop outputs. In the previous example we grew x by appending new values to it. A more efficient practice is to initiate a vector (or other data structure) of the right size and fill the elements. In the example that follows, we create the vector x of the right size and then fill in each element within the for loop. Although this inefficiency is not noticed in this small example, when you perform larger repetitions it will become noticable so you might as well get in the habit of filling rather than growing.

Another example in which we create an empty matrix with 5 rows and 5 columns. The for loop then iterates over each column (note how i takes on the values 1 through the number of columns in the my.mat matrix) and takes a random draw of 5 values from a poisson distribution with mean i in column i:

0 2 2 6 3
0 1 3 2 3
0 0 1 2 2
0 2 2 4 3
2 0 3 6 3