Control Structures Flashcards
Learning if, else, else if statements in R programming languaje
if
if (a > b) {
print(“a is greater than b”)
}
if else
if (a > b) { print("a is greater than b") } else { print("b is greater than a") }
else if
if (a > b) { print("a is greater than b") } else if (a < b) { print("b is greater than a") } else if (a == b) { print("a and b are the same") }
loop: Print elements of a sequence
numbers
Loop over rows of a data frame
for (i in 1:nrow(data_frame)) {
print(data_frame$variable_1[i] + data_frame$variable_2[i])
}
Store for-loop output in a vector
output_vec
for-loop with selection control structure
for (i in 1:nrow(data_frame) { if (a > b) { print("a is greater than b") } else { print("b is greater than a") } }
for-loops with more than two cases
for (i in 1:nrow(data_frame)) { if (a > b) { print("a is greater than b") } else if (a < b) { print("b is greater than a") } else if (a == b) { print("a and b are the same") } }
Which are the 3 types of control structures?
Sequence operations
Selection operations
Repetition operations
What do SEQUENCE operations do?
perform operation one after another in the order they are specified
What do SELECTION operations do?
They test whether a specified condition is TRUE or FALSE and executes diferent action depending on that test outcome.
What do REPETITION operations do?
Allows you to repeat blocks of codes depending on specified conditions.