For loops and vectorization in R
Specifically, we will look at the constructs involved in loops. Note, however, that it is more efficient to use vectorized operations rather than loops, because R is vector-based. We investigate loops here, because they are a good first step in understanding how R works, and then we can optimize this understanding by focusing on vectorized alternatives that are more efficient.
More information about control flows can be obtained by executing the command at the command line:
Help?Control
The control flow commands take decisions and make decisions between alternative actions. The main constructs are for, while, and repeat.
For loops
Let's look at a for
loop in more detail. For this exercise, we will use the Fisher iris
dataset, which is installed along with R by default. We are going to produce summary statistics for each species of iris in the dataset.
You can see some of the iris data by typing in the following command at the command prompt:
head(iris)
We...