# Loops

A loop can be used to perform the same function repeatedly. For example:

`for(i in 1:3){x12[i] <- x12[i] + 1}`
1. `for(i in 1:3){}` sets up the loop to run over three values of i, 1, 2, and 3 for whatever commands are entered in the curly brackets {}.
2. `x12[i]` indicates the ith entry in x12. When i = 1, `x12[i]` is the same as `x12`. When i = 2, `x12[i]` is the same as `x12`.
3. `x12[i] <- x12[i] + 1`

Here the value in x12[i] is replaced by the value in x12[i] plus 1.

In this case the same result is obtained more simply by:

`x12 <- x12 + 1`

since R will perform the function on each entry of `x12`.

A generalization if the function is to be applied to each entry of x12 would be the following.

`for(i in 1:length(x12)){x12[i] <- x12[i] + 1}`

Here i runs from one to the length of the `x12` vector.

The use of a temporary variable named i is arbitrary, another name could be used.

`for(Joe in 1:length(x12)){x12[Joe] <- x12[Joe] + 1}`

You might choose to apply a function only to entries for which a certain criterion is true.

`for(i in 1:length(x12)){if(x12[i] < 4){x12[i] <- x12[i] + 1}}`

Here the `if()` statement controls which entries in the vector `x12` are modified.

In this case, only those entries that are less than 4 have 1 added.

Another way to accomplish the same thing would be as follows.

`index12 <- x12 < 4x12[index12] <- x12[index12] + 1`

Minimizing the use of loops can make R programs more efficient. Often the use of a loop can be avoided if operations are performed on whole objects at a time, as in:

`x12 <- x12 + 1`

Next:  Working with Data Sets