R-FlowControl

If/else

The if loop will only run a block of code if a certain condition is TRUE. It can be paired with else statements to create an if/else loop. This will work similarly to an if/else loop in other programming languages, though the syntax may be different.

if(test_condition){
some_action
}

If there's something you want to happen, even if the test condition isn't true, you would use an if/else, where the syntax usually looks like this:

if(test_expression){
some_action
}else{
some_other_action
}

Even if the test_expression isn't true, some_other_action will still happen. Finally, you can evaluate multiple test conditions with if/else if/else, as shown in the following syntax:

if(test_expression){
some_action
}else if(another_test_expression){
some_other_action
}else{
yet_another_action
}
}

For loop

For loops are often used to go through every column or row of a dataframe in R.

for(i in a range of numbers){
some_action
}

The R function seq_along() is very helpful for the for loops, because it automatically moves along the number of columns of the dataframe (if that's the input) or more generally, iterates along the number of items contained in whatever is input into it.

nrow(iris)
[1] 150
seq_along(iris)
[1] 1 2 3 4 5

While loop

Versus the for loop, which walks through an iterator (usually, this is a sequence of numbers), a while loop will not iterate through a sequence of numbers for you. Instead, it requires you to add a line of code inside the body of the loop that increments or decrements your iterator, usually i. Generally, the syntax for a while loop is as follows:

while(test_expression){
some_action
}

Here, the action will only occur if the test_expression is TRUE. Otherwise, R will not enter the curly braces and run what's inside them. If a test expression is never TRUE, it's possible that a while loop may never run!

A classic example of a while loop is one that prints out numbers, such as the following:

i = 0
while(i <= 5){
print(paste("loop", i))
i = i + 1
}
Page last modified on April 20, 2021, at 04:50 AM
Powered by PmWiki