3.3 Loop
We very often want to execute codes multiple times with the same or similar conditions. There are two basic forms of repetition statement in R:
- while loop: repeat as long as condition is true, and
- for loop over a vector: repeat for each element in the vector.
- we can loop over a character vector
- An important special case for for loop is over an integer vector.
3.3.1 While loop
The syntax of while loop is as follows:
The following example shows how to calculate the sum of all integers from 1 to 10.
3.3.2 Loop over vectors
We can define a vector and construct a for loop that executes for each element in the vector:
## Amy
## Tom
3.3.3 For Loop over integers
Loops that are based on the value of an integer variable. It increases by the same amount each time, and ends when the variable reaches a specified value
The syntax for a for loop is simple.
The following example shows how to calculate the sum of all integers from 1 to 10.
## [1] 55
3.3.4 Simple loop using which
If the previous chapter, we have mentioned which() function that returns all the row numbers that satisfy a condition.
Let see the following example that finds out only number divisible by 5 between integers from 0 to 10.
## [1] 5 10 15 20
Alternatively, we can use which() and ifelse()
## [1] 5 10 15 20
3.3.5 Simple loop using ifelse
R can be more efficient if conditional statements are just comparing numeric vectors element by element. We can use the function ifelse() instead of a foor loop.
Consider the following example that first checks for each element of x, whether it is greater than zero or not, and if it is greater than zero, it would get the value 1 and zero otherwise.
x <- c(1,2,-1,-2)
y <- c()
for (i in 1:length(x)){
if (x[i]>0){
y[i] <- 1
} else{
y[i] <- 0
}
y[i]
}
y
## [1] 1 1 0 0
This can be done more compactly using if-else
## [1] 1 1 0 0
In another more practical example, we want to determine if the stock price today is higher than yesterday.
## Lag.1
## [1,] NA
## [2,] 1
## [3,] 1
## [4,] 0
## [5,] 1
In this example, up is the indicator functions to see if today price is higher than yesterday price.