Control Structure#
Learning objectives
Questions:
How do I use If-Then-Else structure?
How do I use For loops?
How do I use While loops?
Objectives:
Write conditional statement with
if...else
andelseif()
Write and understand
for()
loop
Keypoints:
“Use
if
andelse
”“Use
for
loop “
if-else
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")
}
a <- 5
response <- ifelse(a>3,"a is bigger than 3","a is not bigger than 3")
response
class(response)
For Loop
Full Syntax:
for (iterator in sequence){
do task
}
Example:
for (i in 1:5){
print(i)
}
for (i in seq(1,5,2)){
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 task
}
Example:
a <- 1
while (a<5){
print(a)
a <- a+1
}