This lesson is being piloted (Beta version)

Control Structure

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How do I use If Else structure?

  • How do I use For Loop structure

  • How do I use While Loop structure

Objectives
  • Write conditional statement with if...else and elseif()

  • Write and understand for() loop

if-else

Syntax:

if

if (condition){
  do task
}

if…else

if (condition1){
  do task 1
} else {
  do the rest
}

if…elseif…else

if (condition1){
  do task 1
} else if (condition2) {
  do task 2
} else {
  do the rest
}

ifelse()

ifelse(condition,action if true,action if false)

Examples

a <- 5
if (a>3){
  print("a is bigger than 3")
a <- 5
if (a>3){
  print("a is bigger than 3")
} else {
  print("a is NOT bigger than 3")
}
a <- 5
if (a>3){
  print("a is bigger than 3")
} else if (a==3) {
  print("a equals to 3")
} else {
  print("a is less than 3")
}

```r
a <- 5
ifelse(a>3,"a is bigger than 3","a is not bigger than 3")

For Loop

Full Syntax:

for (iterator in sequence){
  do task
}

Example:

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

Short Syntax

for (i in 1:5) print(i)
for (i in seq(1,5)) print(letters[i])

While Loop

Syntax

while (this condition is true){
  do a thing
}

Example:

a <- 1
while (a<5){
  print(a)
  a <- a+1
}

Key Points

  • Use if and else

  • Use for loop