05 – Control Structures

Sebastian Raschka 07/14/2020

Source file: https://github.com/rasbt/R-notes/blob/master/05-control-structures.Rmd

Control Structures in R

If-else Statements

  1. We can use an if statement without the else, like so:
# ...
if(some_condition) {
  # code that is executed if some_condition is TRUE
}
# ...
  1. The typical if-else approach:
# ...
if(some_condition) {
  # code that is executed if some_condition is TRUE
} else {
  # code that is executed if some_condition is FALSE
}
# ...
  1. Using elif:
# ...
if(some_condition1) {
  # code that is executed if some_condition1 is TRUE
} else if(some_condition_2) {
  # code that is executed if some_condition2 is TRUE
}
else {
  # code that is executed if some_condition1 is FALSE
  # and some_condition2 is FALSE
}
# ...
num <- 15

if(num%%3 == 0 & num%%5 == 0) {
    print("FizzBuzz")
} else if(num%%3 == 0) {
    print("Fizz")
} else if (num%%5 == 0) {
    print("Buzz")
} else {
    print(num)
}

## [1] "FizzBuzz"

While Loops

counter <- 1
while(counter <= 5) {
  print(counter)
  counter <- counter + 1
}

## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

For Loops

for(i in 1:5) {
  print(i)
}

## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

m = 10

n_minus_1 <- 1
n_minus_2 <- 0
cat("# 1 :", n_minus_2, "\n") 

## # 1 : 0

cat("# 2 :", n_minus_1, "\n") 

## # 2 : 1

for(i in 3:m) {
  val = n_minus_1 + n_minus_2
  cat("#", i, ":", val, "\n")
  n_minus_2 <- n_minus_1
  n_minus_1 <- val
}

## # 3 : 1 
## # 4 : 2 
## # 5 : 3 
## # 6 : 5 
## # 7 : 8 
## # 8 : 13 
## # 9 : 21 
## # 10 : 34
vec <- c("H", "e", "l", "l", "o") 
for(i in vec) {
  print(i)
}

## [1] "H"
## [1] "e"
## [1] "l"
## [1] "l"
## [1] "o"
vec <- c("H", "e", "l", "l", "o") 
for(i in seq_along(vec)) {
  print(i)
}

## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

Repeat and Break

counter <- 1
repeat {
  counter <- counter + 1
  if(counter >= 5){
    break
  }
}
print(counter)

## [1] 5
vec <- c("H", "e", "l", "l", "o") 
for(i in vec) {
  if(i == "l"){
    break
  }
  print(i)
}

## [1] "H"
## [1] "e"

Next

vec <- c("H", "e", "l", "l", "o", "W", "o", "r", "l", "d") 
for(i in seq_along(vec)) {
  if(i %% 3 == 0){
    next
  }
  print(vec[i])
}

## [1] "H"
## [1] "e"
## [1] "l"
## [1] "o"
## [1] "o"
## [1] "r"
## [1] "d"

Loop functions / apply functions

data <- list(c(1., 2., 3.), c(4., 5., 6., 7.))
lapply(data, sum)

## [[1]]
## [1] 6
## 
## [[2]]
## [1] 22
data <- list(c(1., 2., 3.), c(4., 5., 6., 7.))
sapply(data, sum)

## [1]  6 22