Control Flow
Use Cases & Syntax
Used to test if a specific case is true or false
Short-circuit evaluation:
Test if all conditions are true
Test if any conditions are true
Test if a condition is not true
Conditional evaluation
If statement: run code if this statement is true
Only used at the beginning of a conditional statement
Else if statement: if previous statements aren't true, try this
Can be used an unlimited number of times in an if statement
Else statement: catch-all for anything outside of prior statements
Only used to end a conditional statement
Inputs:
#If statement
a <- 2
b <- 1
if (a > b){
print("a is greater than b")}
#Else if statement
x <- 10
y <- 10
if (x > y){
print("x is greater than y")
} else if (x <= y){
print("x is less than or equal to y")
}
#Else statement
d <- 3
if (d > 5){
print("d is greater than 5")
} else if (d == 5){
print("d is equal to 5")
} else {
print("d is less than or equal to 5")
}Outputs:
Loops
Repeats a block of code a specified number of times or until some condition is met
While loop
For loop
Use break to terminate loop
Inputs:
Outputs:
Comparison Operators
>
Greater than
<
Less than
>=
Greater than or equal
<=
Less than or equal
==
Exactly equal
!=
Not equal to
&
Entry wise and
Input:
Output:
Resources
R Documentation: Conditional Execution
R Documentation: Repetitive Execution
Last updated
