Introduction
In this article, we will discuss how to use one of the most common and widely used decision-making statements in R. Decision making is very important in any programming language.In this article, we will discuss how to use one of the most common and widely used decision-making statements in R. Decision making is very important in any programming language.
Decision making involves creating multiple conditions that are to be tested by the program, together with statements that will be executed when a condition is true, and optionally, the statements that are to be executed when the condition is false.
R supports different decision-making statements and we will discuss one of them which is the if statement.
If Statement
If statement controls exactly which operations are carried out in a given chunk of code. If a statement runs a block of code only if a certain condition is true. If a statement consists of a Boolean followed by one or more statements.
The statement takes the syntax given below.
if (boolean_expression) {
# statement(s) to be executed if the Boolean expression evaluates to true.
}
The condition is placed in parentheses after the if keyword. This condition must be a boolean expression.
If the specified condition is found to be true, the statements inside the curly brace will be executed. If the specified condition evaluates to a “false”, the code in the braces is skipped and the statements immediately after the if statement will be executed.
Consider the example given below: Consider the example given below.
y <- 12L
if (is.integer(y)) {
print("Y is an Integer")
}
On execution, the program will give you the following output.
[1] "Y is an Integer"
The specified condition checks whether variable y is an integer or not. Since the variable is an integer, the condition was evaluated to a true, hence, the statement below was executed.
Here is another example showing how to use the if statement.
age <- 16
if (age < 18) {
print("Your age is less than 18 years")
}
The code will return the following upon execution.
[1] "Your age is less than 18 years"
In the if expression, we are checking whether the value of variable age is less than 18. We had set the value of age to 16. Since the condition evaluates to a true, the statement below was executed.
The bad thing about the if expression is that nothing is done when the condition is false. Let us change the value of age to 20.
age <- 20
if (age < 18) {
print("Your age is less than 18 years")
}
Since the value of age is greater than 18, the condition will be evaluated a false. The code will return nothing.
Here is another example.
a <- 3
mynumber <- 4
if (a <= mynumber) {
a <- a^2
}
a
[1] 9
In this case, when the condition a<=mynumber is evaluated, the result is TRUE since 3 is less than 4. That means the code inside the braces is executed, which sets a to a^2, or 9.
Use of matrix and vector in an if statement
The if statement offers a huge amount of flexibility, you can place any kind of code in the braced area, including more if statements, enabling your program to make a sequence of decisions.
To illustrate a more complicated if statement, consider the following two new objects.
myvec <- c(2.73, 5.40, 2.15, 5.29, 1.36, 2.16, 1.41, 6.97, 7.99, 9.52)
myvec
# [1] 2.73 5.40 2.15 5.29 1.36 2.16 1.41 6.97 7.99 9.52
mymat <- matrix(c(2, 0, 1, 2, 3, 0, 3, 0, 1, 1), 5, 2)
mymat
# [,1] [,2]
# [1,] 2 0
# [2,] 0 3
# [3,] 1 0
# [4,] 2 1
# [5,] 3 1
Use these two objects in the code chunk given here.
if (any((myvec - 1) > 9) || matrix(myvec, 2, 5)[2, 1] <= 6) {
cat("Condition satisfied --\n")
new.myvec <- myvec
new.myvec[seq(1, 9, 2)] <- NA
mylist <- list(aa = new.myvec, bb = mymat + 0.5)
cat("-- a list with", length(mylist), "members now exists.")
}
Send this to the console, and it produces the following output.
# Condition satisfied --
# -- a list with 2 members now exists.
An object on my list has been created that you can examine.
> mylist
$aa
[1] NA 5.40 NA 5.29 NA 2.16 NA 6.97 NA 9.52
$bb
[,1] [,2]
[1,] 2.5 0.5
[2,] 0.5 3.5
[3,] 1.5 0.5
[4,] 2.5 1.5
[5,] 3.5 1.5
In this example, the condition consists of two parts separated by an OR statement using ||, which produces a single logical result. Let’s walk through it.
The first part of the condition looks at myvec, takes 1 away from each element, and checks whether any of the results are greater than 9. If you run this part on its own, it yields FALSE.
> myvec <- c(1.73, 4.40, 1.15, 4.29, 0.36, 1.16, 0.41, 5.97, 6.99, 8.52)
> (myvec - 1) > 9
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> any((myvec - 1) > 9)
[1] FALSE
The second part of the condition uses positional matching in a call to the matrix to construct a two-row, five-column, column-filled matrix using entries of the original myvec. Then, the number in the second row of the first column of that result is checked to see whether it’s less than or equal to 6, which it is.
# Create a matrix from a vector
matrix(myvec, 2, 5)
# Extract a specific element from the matrix
matrix(myvec, 2, 5)[2, 1]
# Check if a specific element in the matrix is less than or equal to 6
matrix(myvec, 2, 5)[2, 1] <= 6
This means the overall condition being checked by the if statement will be FALSE||TRUE, which evaluates as TRUE.
any((myvec - 1) > 9) || matrix(myvec, 2, 5)[2, 1] <= 6
[1] TRUE
As a result, the code inside the braces is accessed and executed. First, it prints the "Condition satisfied" string and copies myvec to new. myvec. Using seq, it then accesses the odd-numbered indexes of new myvec and overwrites them with NA.
Next, it creates my list. In this list, new myvec is stored in a member named aa, and then it takes the original my mat, increases all its elements by 0.5, and stores the result in bb. Lastly, it prints the length of the resulting list.
Summary
In this article, I explained how to use one of the most common and widely used decision-making statements, that is, the if statement in R. I demonstrated how to define the syntax of the if statement. Several examples along with proper coding snippets and outputs were discussed. In the end, I also demonstrated how to use vectors and matrix inside of if statements.