if (condition) {
# code to be executed if the condition is TRUE
}
Control Flow - If Else Statement
Control Flow - If Else Statement
Control Flow is a critical concept in programming that allows for the execution of code in a non-linear fashion.
Control flow structures in R allow you to specify which pieces of code are to be executed and in what order. These structures enable you to create dynamic programs that can make decisions, repeat actions, and handle different input scenarios.
'if'
Statement
The if
statement is a fundamental component of flow control in R. It evaluates a given condition, and if the condition is TRUE
, the block of code within the if
statement is executed. If the condition is FALSE
, the if
statement is ignored, and the program continues to the next line of code outside the if
block.
The basic syntax of an if
statement in R is as follows:
Example 1: Checking for positive number
<- 5
x if (x > 0) {
print("x is positive")
}
[1] "x is positive"
if else
statement
The else
clause can be added to execute code when the condition is FALSE
.
<- -3
x if (x > 0) {
print("x is positive")
else {
} print("x is not positive")
}
[1] "x is not positive"
Example 2: Validating Age for Voting
In this example, the if statement checks whether a person is eligible to vote based on their age. If the age is 18 or above, a message is printed indicating eligibility to vote.
<- 20
age if (age >= 18) {
print("You are eligible to vote.")
}
[1] "You are eligible to vote."
Example 4: Checking for Non-Negative Number
This example demonstrates the use of the if statement to check whether a number is non-negative (i.e., either positive or zero).
<- -5
number if (number >= 0) {
print(paste(number, "is a non-negative number."))
else {
} print(paste(number, "is a negative number."))
}
[1] "-5 is a negative number."
Example 5: Validating Password Length
This example uses the if-else statement to validate the length of a password.
<- "Nasir"
password if (nchar(password) >= 8) { print("The password length is valid.")
else {
} print("The password length is invalid. It must be at least 8 characters long.")
}
[1] "The password length is invalid. It must be at least 8 characters long."
Example 6: Changing variable to factor datatype
# Using a loop to go through each column of the dataset
for (var in names(mtcars)) {
# Check if the current column name is one of the desired columns
if (var %in% c("cyl", "am", "vs", "gear", "carb")) {
<- as.factor(mtcars[[var]])
mtcars[[var]] else {
} # Do nothing (or any other operation you want) for other columns
next
}
}
# Checking the structure of the modified dataset
str(mtcars)
'data.frame': 32 obs. of 11 variables:
$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
$ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
$ disp: num 160 160 108 258 360 ...
$ hp : num 110 110 93 110 175 105 245 62 95 123 ...
$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
$ wt : num 2.62 2.88 2.32 3.21 3.44 ...
$ qsec: num 16.5 17 18.6 19.4 17 ...
$ vs : Factor w/ 2 levels "0","1": 1 1 2 2 1 2 1 2 2 2 ...
$ am : Factor w/ 2 levels "0","1": 2 2 2 1 1 1 1 1 1 1 ...
$ gear: Factor w/ 3 levels "3","4","5": 2 2 2 1 1 1 1 2 2 2 ...
$ carb: Factor w/ 6 levels "1","2","3","4",..: 4 4 1 1 2 1 4 2 2 4 ...
For multiple conditions, use else if
.
<- 0
x if (x > 0) {
print("x is positive")
else if (x < 0) {
} print("x is negative")
else {
} print("x is zero")
}
[1] "x is zero"
Example 7: Grade Assignment
Assign grades based on numeric scores.
<- 85
score
if (score >= 90) {
print("Grade: A")
else if (score >= 80) {
} print("Grade: B")
else if (score >= 70) {
} print("Grade: C")
else if (score >= 60) {
} print("Grade: D")
else {
} print("Grade: F")
}
[1] "Grade: B"
Example 8: Day of the Week
Display a message based on the day of the week.
<- "Sunday"
day
if (day == "Saturday" || day == "Sunday") {
print("It's the weekend!")
else if (day == "Monday") {
} print("Start of the work week!")
else if (day == "Friday") {
} print("Almost the weekend!")
else {
} print("It's a weekday.")
}
[1] "It's the weekend!"
Example 9: Age Groups
Categorize individuals into age groups.
<- 25
age
if (age <= 12) {
print("Child")
else if (age <= 19) {
} print("Teenager")
else if (age <= 35) {
} print("Young Adult")
else if (age <= 60) {
} print("Adult")
else {
} print("Senior")
}
[1] "Young Adult"
Example 10: Checking Number Properties
Determine if a number is negative, zero, or positive and if it’s even or odd.
<- 7
num
if (num < 0) {
print("Negative")
if (num %% 2 == 0) {
print("Even")
else {
} print("Odd")
}else if (num == 0) {
} print("Zero")
else {
} print("Positive")
if (num %% 2 == 0) {
print("Even")
else {
} print("Odd")
} }
[1] "Positive"
[1] "Odd"
A larger perspectives of if-else
Example 11: Categorizing Student Grades
Suppose we have a vector containing scores of multiple students. We want to categorize each score into a grade and store the results in a new vector.
# Sample student scores
<- c(95, 87, 78, 85, 62, 90, 73, 88, 81, 56)
scores
# Initialize an empty vector for grades
<- character(length(scores))
grades
# Categorize each score
for (i in 1:length(scores)) {
if (scores[i] >= 90) {
<- "A"
grades[i] else if (scores[i] >= 80) {
} <- "B"
grades[i] else if (scores[i] >= 70) {
} <- "C"
grades[i] else if (scores[i] >= 60) {
} <- "D"
grades[i] else {
} <- "F"
grades[i]
}
}
# Print the grades
print(grades)
[1] "A" "B" "C" "B" "D" "A" "C" "B" "B" "F"
Example 12: Checking Positive, Negative, and Zero Values
Given a vector of numbers, determine how many are positive, negative, and zero.
# Sample vector of numbers
<- c(-5, 2, 9, 0, -1, 0, 7, -3, 0, 4)
numbers
# Initialize counters
<- 0
count_positive <- 0
count_negative <- 0
count_zero
# Check each number
for (num in numbers) {
if (num > 0) {
<- count_positive + 1
count_positive else if (num < 0) {
} <- count_negative + 1
count_negative else {
} <- count_zero + 1
count_zero
}
}
# Print results
cat("Positive numbers:", count_positive, "\n")
Positive numbers: 4
cat("Negative numbers:", count_negative, "\n")
Negative numbers: 3
cat("Zeros:", count_zero, "\n")
Zeros: 3
Example 13: Group Ages
Given a vector of ages, categorize them into different age groups.
# Sample ages
<- c(25, 42, 15, 33, 68, 72, 19, 56, 9, 31)
ages
# Initialize an empty vector for age groups
<- character(length(ages))
age_groups
# Categorize each age
for (i in 1:length(ages)) {
if (ages[i] <= 12) {
<- "Child"
age_groups[i] else if (ages[i] <= 19) {
} <- "Teenager"
age_groups[i] else if (ages[i] <= 35) {
} <- "Young Adult"
age_groups[i] else if (ages[i] <= 60) {
} <- "Adult"
age_groups[i] else {
} <- "Senior"
age_groups[i]
}
}
# Print the age groups
print(age_groups)
[1] "Young Adult" "Adult" "Teenager" "Young Adult" "Senior"
[6] "Senior" "Teenager" "Adult" "Child" "Young Adult"
ifelse
statement
The ifelse()
function in R is a vectorized alternative to the if-else statement, allowing for more concise and efficient conditional operations on vectors. It evaluates a condition for each element of a vector and returns a new vector with values assigned based on whether the condition is TRUE
or FALSE
.
The basic syntax of the ifelse()
function in R is as follows:
ifelse(test_expression, x, y)
• test_expression: The condition to be evaluated.
• x: The value to be returned in the new vector if the test_expression is TRUE.
• y: The value to be returned in the new vector if the test_expression is FALSE.
Example 14: Categorizing Numbers as Positive or Negative
In this example, the ifelse()
function is used to categorize a vector of numbers as either “Positive” or “Negative”.
<- c(-3, 2, -1, 5, -4)
numbers <- ifelse(numbers > 0, "Positive", "Negative")
categories
print(categories)
[1] "Negative" "Positive" "Negative" "Positive" "Negative"
Example 15: Assigning Pass or Fail to Student Grades
This example demonstrates the use of the ifelse()
function to assign “Pass” or “Fail” to a vector of student grades.
<- c(85, 40, 76, 59, 90)
grades <- ifelse(grades >= 60, "Pass", "Fail")
results print(results)
[1] "Pass" "Fail" "Pass" "Fail" "Pass"
Example 16: Recoding Factors
Suppose you have a vector of grades and you want to recode them into “Pass” and “Fail”.
<- c("A", "B", "C", "D", "F")
grades <- ifelse(grades %in% c("A", "B", "C"), "Pass", "Fail")
status print(status)
[1] "Pass" "Pass" "Pass" "Fail" "Fail"
Example 17: Handling Missing Values
Replace NA
values in a vector with the mean of non-missing values.
<- c(1, 2, NA, 4, NA, 6)
data <- mean(data, na.rm = TRUE)
mean_value <- ifelse(is.na(data), mean_value, data)
filled_data print(filled_data)
[1] 1.00 2.00 3.25 4.00 3.25 6.00
Example 18: Determining the Parity of Numbers
This example uses the ifelse()
function to determine whether the numbers in a vector are odd or even.
<- c(1, 2, 3, 4, 5)
numbers <- ifelse(numbers %% 2 == 0, "Even", "Odd")
parity print(parity)
[1] "Odd" "Even" "Odd" "Even" "Odd"
Exercise
Exercise 1: Temperature Classification
Given a vector of temperatures in Celsius, classify each temperature as “Cold” if it’s below 10°C, “Moderate” if it’s between 10°C and 25°C, and “Hot” if it’s above 25°C. Store the results in a new vector and print it.
<- c(15, 8, 27, 12, 30, 9, 23, 5, 19) temperatures
Exercise 2: Counting Vowel Occurrences
You have a vector containing single characters. Write a program to count the number of occurrences of vowels (a, e, i, o, u) in the vector.
<- c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'o', 'p', 'u') chars
Exercise 3: Student Pass/Fail Status
Given a vector of student scores, determine how many students passed and how many failed. Assume a passing score is 50 or above.
<- c(45, 56, 67, 48, 90, 75, 33, 52) scores
Exercise 4: Categorizing Heights
You have a vector containing heights of various individuals in centimeters. Categorize each height as “Short” if below 160cm, “Average” if between 160cm and 180cm, and “Tall” if above 180cm. Store the results in a new vector.
<- c(155, 162, 171, 185, 150, 178, 182, 165, 170) heights
Exercise 5: Price Discounts
You have a vector containing the prices of items in a store. Any item that costs more than $100 gets a 10% discount, while items costing $50 or less get a 5% discount. Adjust the prices according to these criteria using the ifelse()
function.
<- c(45, 150, 75, 30, 110, 60) prices
Exercise 6: Student Remarks
Given a vector of student scores, provide remarks based on the following criteria:
90 and above: “Excellent”
75 to 89: “Very Good”
60 to 74: “Good”
50 to 59: “Average”
Below 50: “Poor”
Use the ifelse()
function to categorize the student scores into the respective remarks.
<- c(85, 93, 67, 58, 72, 45) scores
Exercise 7: Weather Condition
You have a vector containing daily average temperatures. Classify each day’s weather as:
Below 0°C: “Freezing”
0°C to 10°C: “Cold”
11°C to 20°C: “Mild”
21°C to 30°C: “Warm”
Above 30°C: “Hot”
Use the ifelse()
function to categorize the temperatures.
<- c(15, -2, 28, 8, 20, 32) temperatures