Everything you need to know about conditional statements to start building and working with them.
Published in · 10 min read · Jul 19, 2020
--
Relational operators tell us how R objects relate, and logical operators allow us to combine logical values. R provides a way to use the results from these operators to change the behaviour of our own R scripts. This is done by if
and else
statements.
The if
statement takes a condition; if the condition evaluates to TRUE
, the R code associated with the if
statement is executed.
if (condition) {
expr
}
The condition to check appears inside parentheses, while the R code that has to be executed if the condition is TRUE
, follows in curly brackets ( expr
).
Here is an example:
x <- -3
if (x < 0) {
print("x is a negative number")
}
Suppose we have a variable x
equal to -3. If this x
is smaller than zero, we want R to print out “x is a negative number”
. We can do this by using the if
statement. We first assign the variable x
, and then write the if
condition.
In this case, assign -3 to x
, and set the if
condition to be true if x
is smaller than 0 (x < 0
).
If we run the example code, we indeed see that the string “x is a negative number” gets printed out.
However, if we were to change x
to 5, and re-run the code, the condition would be FALSE
, and the print statement would not be executed.
For you to try
Suppose you are given the following variables:
medium
— information about the social websitenum_views
— the actual number of views that particularmedium
had on the last day of your recordings of social profile views
# Variables related to your last day of recordings
medium <- "LinkedIn"
num_views <- 14
Code an if
statement that prints "You are popular"
if the num_views
variable exceeds 15.
Hint
Recall the syntax of the if
statement:
if (condition) {
expr
}
Here is an example of the if statement for medium
that prints out which social website is being shown:
if (medium == "LinkedIn") {
print("Showing LinkedIn information")
}
Solution
# Write the if statement for num_views
if (num_views > 15) {
print("You are popular!")
}
The else
statement does not need an explicit condition; instead, it has to be used with an if
statement. The code associated with the else
statement gets executed whenever the condition of the if
condition is not TRUE
.
if (condition) {
expr1
} else {
expr2
}
Suppose we want to print out for the following scenarios:
- if
x
is less than 0, print“x is a negative number”
- if
x
is greater than or equal to 0, print“x is either a positive number or zero”
The second condition occurs whenever x < 0
is not met. So, we can simply add an else
statement.
x <- -3
if (x < 0) {
print("x is a negative number")
} else {
print ("x is either a positive number or zero")
}
If we ran the code with x
equal to -3, we would get the printout “x is a negative number”
.
However, if x
was 5 instead, then we would get the printout “x is either a positive number or zero”
. The x < 0
condition is not satisfied, so R turns to the expression in the else statement.
For you to try
For this for you to try, you’ll be using the same variables as the previous for you to try.
# Variables related to your last day of recordings
medium <- "LinkedIn"
num_views <- 14
Code control structures using an if
and else
statement that accomplishes the following:
- If
medium
is LinkedIn, print"Showing LinkedIn information"
, otherwise, print"Unknown medium
". - If
num_views
exceeds 15 views, print"You're popular!"
. If theif
condition is not met, print"Try to be more visible!"
.
Hint
Recall that you can only use an else
statement in combination with an if
statement. The else
statement does not require a condition; its corresponding code is simply run if all the preceding conditions in the control structure are FALSE
. Here is the syntax for its usage:
if (condition) {
expr1
} else {
expr2
}
It’s important that the else
keyword comes on the same line as the closing bracket of the the if
part!
Solution
# Variables related to your last day of recordings
medium <- "LinkedIn"
num_views <- 14# Control structure for medium
if (medium == "LinkedIn") {
print("Showing LinkedIn information")
} else {
print("Unknown medium")
}# Control structure for num_views
if (num_views > 15) {
print("You're popular!")
} else {
print("Try to be more visible!")
}
There are also cases when you want to customize your programs even further. The else if
statement comes in between the if
and else
statement. The else if
condition is checked if the first condition is not satisfied. If the second condition is then met, then the code inside it is executed.
if (condition1) {
expr1
} else if (condition2) {
expr2
} else {
expr3
}
Suppose we wanted another printout if x
equals exactly 0. With the previous code block, that wouldn’t be possible. Instead, we would need another condition check. We can achieve this by using the else if
statement.
Say we now want to print out for the following conditions:
- if
x
less than 0, print“x is a negative number”
- if
x
equals 0, print“x is zero”
- otherwise, print out
“x is a positive number”
We can accomplish this by adding the else if
, together with a new print statement, and adapt the message we print on the else statement.
x <- -3
if (x < 0) {
print("x is a negative number")
} else if (x == 0) {
print("x is zero")
} else {
print("x is a positive number")
}
R processes this control structure depending on the conditions met.
In the case x
is -3, the condition for the if
statement evaluates to TRUE
, so “x is a negative number”
is printed out, and R ignores the rest of the statements.
If x
equals 0, R will first check the if
condition, sees that it is FALSE
, and will then head over to the else if
condition. This condition, x==0
, evaluates to TRUE
, so “x is zero”
gets printed out, and R ignores the else
statement entirely.
If x
equals 5, the if
condition evaluates to FALSE
, so does the else if
condition, so R executes the else
statement, printing “x is a positive number”
.
As soon as R stumbles upon a condition that evaluates to TRUE
, R executes the corresponding code and then ignores the rest of the control structure. This becomes important if the conditions you list are not mutually exclusive.
Consider the following example, that sees if a number is divisible by 2 or by 3.
x <- -6
if (x %% 2 == 0) {
print("divisible by 2")
} else if (x %% 3 == 0) {
print("divisible by 3")
} else {
print("not divisible by 2 nor by 3...")
}
When x
equals 6, the first condition evaluates to TRUE
, so R prints out “divisible by 2”
.
R then exits the control structure and will not look at the rest of the statements. So although the second condition, for the else if
part, would evaluate to TRUE
, nothing gets printed out.
For you to try
Using your code from the previous for you to try, add code to both control structures such that:
- R prints out
"Showing Facebook information"
ifmedium
is equal to “Facebook”. Keep in mind that R is case sensitive. - If
num_views
is between 15 (inclusive) and 10 (exclusive) print out"Your number of views is average"
.
Hint
The else if
statement allows you to further customize your control structure. You can add as many else if
statements as you like. Keep in mind that R ignores the remainder of the control structures once a condition has been found that is TRUE
and the corresponding expressions have been executed. Here is an overview of the syntax:
if (condition1) {
expr1
} else if (condition2) {
expr2
} else if (condition3) {
expr3
} else {
expr4
}
Again, it is important that the else if
keywords comes on the same line as the closing as the closing bracket of the previous part of the control construct.
Solution
# Variables related to your last day of recordings
medium <- "LinkedIn"
num_views <- 14# Control structure for medium
if (medium == "LinkedIn") {
print("Showing LinkedIn information")
} else if (medium == "Facebook") {
print("Showing Facebook information")
} else {
print("Unknown medium")
}# Control structure for num_views
if (num_views > 15) {
print("You're popular!")
} else if (num_views <= 15 & num_views > 10) {
print("Your number of views is average")
} else {
print("Try to be more visible!")
}
For you to try (2)
You can do anything you want inside if-else constructs. You can even put in another set of conditional statements.
Examine the following code:
if (number < 10) {
if (number < 5) {
result <- "extra small"
} else {
result <- "small"
}
} else if (number < 100) {
result <- "medium"
} else {
result <- "large"
}
print(result)
Consider the following statements:
- If
number
is set to 6,“small”
gets printed. - If
number
is set to 100,"medium"
is printed. - If
number
is set to 4,"extra small"
gets printed. - If
number
is set to 2500, R will generate an error, asresult
will not be defined.
Determine which of the statements are true.
Solution
- Suppose that
number
is 6. The condition of theif
block (number < 10
) is satisfied, so we enter the second if-else flow. Theif
condition of the second flow (number < 5
) is not met, so theelse
code is executed (result <- "small"
). Thus, the statement “Ifnumber
is set to 6,“small”
gets printed” is true. - Suppose that
number
is 100. The first condition from the if statement (number < 10
) and the second condition from the else if condition (number < 100
) do not hold. Thus, the code within theelse
block is executed, and"large"
is printed. The statement “Ifnumber
is set to 100,"medium"
is printed” is false. - Suppose that
number
is 4. The condition of theif
block (number < 10
) is met, so the second if-else control is entered. Theif
condition of the second if-else control (number < 5
) is met, so the codereturn <- "extra small"
is executed. Thus, the statement “Ifnumber
is set to 4,"extra small"
gets printed” is true. - Suppose that
number
is 2500. The number is neither less than 10, nor less than 100. So, it does not meet either of the conditions and theelse
code is executed instead (result <- “large”
). Thus, the statement “Ifnumber
is set to 2500, R will generate an error, asresult
will not be defined” is false.
This challenge combines relational operators, logical operators, and control constructs.
Consider two variables: li
and fb
, denoting the number of profile views your LinkedIn and Facebook profile had yesterday.
# Variables related to yesterday's profile views.
li <- 15
fb <- 9
Generate a ‘social media score’, sms
, based on the values of li
and fb
, based on the following behaviour:
- If both
li
andfb
are 15 or higher, setsms
equal to double the sum ofli
andfb
. - If both
li
andfb
are strictly below 10, setsms
equal to half the sum ofli
andfb
. - In all other cases, set
sms
equal toli + fb
.
Print the resulting sms
variable.
Hint
# Code the control-flow construct
if (___ & ___) {
sms <- 2 * (li + fb)
} ___ (___) {
sms <- 0.5 * (li + fb)
} else {
sms <- ___
}
Solution
# Variables related to your last day of recordings
li <- 15
fb <- 9# Code the control-flow construct
if (li >= 15 & fb >= 15) {
sms <- 2 * (li + fb)
} else if (li < 10 & fb < 10) {
sms <- 0.5 * (li + fb)
} else {
sms <- li + fb
}# Print the resulting sms to the console
print(sms)
All images, unless specified, are owned by the author. The banner image was created using Canva.