Decision Making in R Programming with Examples
R Programming: Decision Making
Hello students! We’ve
learned about R’s operators, which help us perform calculations and
comparisons. Now, let’s explore how R can make decisions based on those
comparisons. This is called decision making or conditional execution.
In programming,
decision making allows your code to perform different actions based on whether
a certain condition is true or false. Imagine telling R: "IF this
condition is met, THEN do A; OTHERWISE, do B." This ability to control the
flow of your program is fundamental for creating dynamic and responsive code
that can adapt to different situations.
It’s like how you make
decisions in daily life:
●
If it’s raining, then
take an umbrella.
●
If you finish your
homework early, then you can play, else you must keep studying.
●
If it’s Monday, then
we have a lecture. Else if it’s Wednesday, then we have a lab. Else
it’s a different day.
R uses if statements
(and their variations) to implement these decisions.
1. The if Statement
The simplest form of
decision making is the if statement. It checks a condition, and if that
condition is TRUE, a block of code is executed. If the condition is FALSE, the
code block is skipped.
Syntax:
if (condition) {
# Code to execute if the condition is TRUE
}
●
condition: This must be an expression that
evaluates to TRUE or FALSE (a logical value). Usually, this involves relational
operators (e.g., x > 10).
●
{ }: These curly braces define the
"block" of code that belongs to the if statement. It’s a good
practice to always use them, even for a single line of code.
Simple Example:
Let’s say we want to
check if a student passed an exam (score 50 or above).
# Student
score (pass case)
student_score
<- 65
if
(student_score >= 50) {
print("Congratulations! You passed the
exam.")
}
# Student
score (fail case)
student_score_fail
<- 45
if
(student_score_fail >= 50) {
print("This message will NOT be printed
because 45 is not >= 50.")
}
2. The if-else Statement
Often, you want to
perform one action if a condition is TRUE and a different action if the
condition is FALSE. This is where the if-else statement comes in handy.
Syntax:
if
(condition) {
# Code to execute if the condition is TRUE
} else {
# Code to execute if the condition is FALSE
}
Simple Example:
Using the exam score
example, we can now provide feedback for both passing and failing.
# Student
score (pass case)
student_score
<- 65
if
(student_score >= 50) {
print("Congratulations! You passed the
exam.")
} else {
print("Unfortunately, you did not pass.
Please try again.")
}
# Student
score (fail case)
student_score_fail
<- 45
if
(student_score_fail >= 50) {
print("Congratulations! You passed the
exam.")
} else {
print("Unfortunately, you did not pass.
Please try again.")
}
3. The if-else if-else Statement
When you have more than
two possible outcomes or multiple conditions to check in a specific order, you
use if-else if-else. R checks the conditions one by one, from top to bottom. As
soon as it finds a TRUE condition, it executes that block of code and then
skips the rest of the else if and else blocks. If none of the if or else if
conditions are TRUE, the else block (if present) will be executed.
Syntax:
if
(condition1) {
# Code if condition1 is TRUE
} else if
(condition2) {
# Code if condition1 is FALSE and condition2
is TRUE
} else if
(condition3) {
# Code if condition1 and condition2 are FALSE
and condition3 is TRUE
} else {
# Code if ALL preceding conditions are FALSE
}
Simple Example:
Let’s assign letter
grades based on a student’s score.
# Student score example 1
student_score
<- 78
if
(student_score >= 90) {
print("Grade: A")
}
else if (student_score >= 80) {
print("Grade: B")
}
else if (student_score >= 70) {
print("Grade: C")
}
else if (student_score >= 50) {
print("Grade: D")
}
else {
print("Grade: F")
}
#
Try with another score
another_score
<- 40
if
(another_score >= 90) {
print("Grade: A")
}
else if (another_score >= 80) {
print("Grade: B")
}
else if (another_score >= 70) {
print("Grade: C")
}
else if (another_score >= 50) {
print("Grade: D")
}
else {
print("Grade: F") # Printed for another_score = 40
}
Notice the order: it’s
important to check the highest scores first. If we checked student_score >=
50 first, a score of 90 would incorrectly get a "D".
4. Simple Programs Demonstrating Decision
Making
Here are two simple R
programs for your practical session. Type them into your RStudio script editor,
run them, and observe how the output changes based on different input values.
Program 1: Checking Eligibility for a
Discount
This program uses
if-else to determine if a customer is eligible for a discount based on their
purchase amount.
# Program 1: Checking Eligibility for a
Discount
#
— User Input —
#
You can change this value to test different scenarios
purchase_amount
<- 75
cat(paste("Customer’s
purchase amount: $", purchase_amount, "\n"))
#
— Decision Logic —
if
(purchase_amount >= 100) {
# Code to execute if purchase amount is $100
or more
print("Congratulations! You are eligible
for a 10% discount.")
discount_amount <- purchase_amount * 0.10
final_price <- purchase_amount –
discount_amount
cat(paste("Discount amount: $",
discount_amount, "\n"))
cat(paste("Your final price is: $",
final_price, "\n"))
}
else {
# Code to execute if purchase amount is less
than $100
print("To get a discount, purchase $100
or more.")
cat(paste("You need to spend $",
100 – purchase_amount,
" more for a
discount.\n"))
}
#
————————————————–
cat("\n—
Test with a different amount —\n")
#
Second test case
purchase_amount_high
<- 120
cat(paste("Customer’s
purchase amount: $", purchase_amount_high, "\n"))
if
(purchase_amount_high >= 100) {
print("Congratulations! You are eligible
for a 10% discount.")
discount_amount <- purchase_amount_high *
0.10
final_price <- purchase_amount_high –
discount_amount
cat(paste("Discount amount: $",
discount_amount, "\n"))
cat(paste("Your final price is: $",
final_price, "\n"))
}
else {
print("To get a discount, purchase $100
or more.")
cat(paste("You need to spend $",
100 – purchase_amount_high,
" more for a
discount.\n"))
}
Program 2: Categorizing a Number
This program uses an
if-else if-else structure to classify a given number.
# Program
2: Categorizing a Number
# — User
Input —
# You can
change this value to test different scenarios
number_to_check
<- -5
cat(paste("The
number to check is:", number_to_check, "\n"))
# —
Decision Logic —
if
(number_to_check > 0) {
# Code if the number is positive
print("The number is positive.")
} else if
(number_to_check < 0) {
# Code if the number is negative
print("The number is negative.")
} else {
# Code if the number is zero
print("The number is zero.")
}
# ————————————————–
cat("\n—
Test with a different number —\n")
# Second
test case (zero)
number_to_check_zero
<- 0
cat(paste("The
number to check is:", number_to_check_zero, "\n"))
if
(number_to_check_zero > 0) {
print("The number is positive.")
} else if
(number_to_check_zero < 0) {
print("The number is negative.")
} else {
print("The number is zero.")
}
#
————————————————–
cat("\n—
Test with another number —\n")
# Third test
case (positive)
number_to_check_positive
<- 10
cat(paste("The
number to check is:", number_to_check_positive, "\n"))
if
(number_to_check_positive > 0) {
print("The number is positive.")
} else if
(number_to_check_positive < 0) {
print("The number is negative.")
} else {
print("The number is zero.")
}
Concluding Thought:
Decision making statements are incredibly powerful.
They allow your R programs to react intelligently to different data and
situations, making them much more useful for real-world data analysis tasks.
Practice with these examples, and try to think about how you might use if,
if-else, and if-else if-else in your own mini-projects!