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:

  1. while loop: repeat as long as condition is true, and
  2. 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:

while (condition){
  keep doing when condition holds
}

The following example shows how to calculate the sum of all integers from 1 to 10.

n <- 10
i <- 1
sum <- 0
while (i <= n){         # i is the control variable     
  sum <- sum + i        # accumulate i into sum
        i <- i + 1      # increment i by 1
  }

3.3.2 Loop over vectors

We can define a vector and construct a for loop that executes for each element in the vector:

students <- c("Amy", "Tom")
for (student in students){
   cat(student,"\n")
}
## 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.

m <- 1
n <-10
for (i in m:n){
  run as long as condition holds
}

The following example shows how to calculate the sum of all integers from 1 to 10.

n <- 10
sum <- 0
for (i in 1:n){
  sum <- sum + i
} 
sum
## [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.

result <-c()
for (i in 1:20){
  if (i %%5 == 0){
    result <- c(result,i)
  }
}
result
## [1]  5 10 15 20

Alternatively, we can use which() and ifelse()

x <- 1:20
x[which(x%%5==0)]
## [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

x <- c(1,2,-1,-2)
y <- ifelse(x > 0,1,0)
y
## [1] 1 1 0 0

In another more practical example, we want to determine if the stock price today is higher than yesterday.

price <- c(1,2,3,2,4)
L.price <- Lag(price,1)
up <- ifelse(price - L.price > 0,1,0)
up
##      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.