Control Flow - If Else Statement

Author

Dr. Mohammad Nasir Abdullah

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:

 if (condition) { 
   # code to be executed if the condition is TRUE 
   }

Example 1: Checking for positive number

x <- 5
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.

x <- -3
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.

age <- 20
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).

number <- -5 
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.

password <- "Nasir" 
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")) {
    mtcars[[var]] <- as.factor(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.

x <- 0
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.

score <- 85

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.

day <- "Sunday"

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.

age <- 25

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.

num <- 7

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
scores <- c(95, 87, 78, 85, 62, 90, 73, 88, 81, 56)

# Initialize an empty vector for grades
grades <- character(length(scores))

# Categorize each score
for (i in 1:length(scores)) {
  if (scores[i] >= 90) {
    grades[i] <- "A"
  } else if (scores[i] >= 80) {
    grades[i] <- "B"
  } else if (scores[i] >= 70) {
    grades[i] <- "C"
  } else if (scores[i] >= 60) {
    grades[i] <- "D"
  } else {
    grades[i] <- "F"
  }
}

# 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
numbers <- c(-5, 2, 9, 0, -1, 0, 7, -3, 0, 4)

# Initialize counters
count_positive <- 0
count_negative <- 0
count_zero <- 0

# Check each number
for (num in numbers) {
  if (num > 0) {
    count_positive <- count_positive + 1
  } else if (num < 0) {
    count_negative <- count_negative + 1
  } else {
    count_zero <- count_zero + 1
  }
}

# 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
ages <- c(25, 42, 15, 33, 68, 72, 19, 56, 9, 31)

# Initialize an empty vector for age groups
age_groups <- character(length(ages))

# Categorize each age
for (i in 1:length(ages)) {
  if (ages[i] <= 12) {
    age_groups[i] <- "Child"
  } else if (ages[i] <= 19) {
    age_groups[i] <- "Teenager"
  } else if (ages[i] <= 35) {
    age_groups[i] <- "Young Adult"
  } else if (ages[i] <= 60) {
    age_groups[i] <- "Adult"
  } else {
    age_groups[i] <- "Senior"
  }
}

# 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”.

numbers <- c(-3, 2, -1, 5, -4) 
categories <- ifelse(numbers > 0, "Positive", "Negative")

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.

grades <- c(85, 40, 76, 59, 90) 
results <- ifelse(grades >= 60, "Pass", "Fail") 
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”.

grades <- c("A", "B", "C", "D", "F")
status <- ifelse(grades %in% c("A", "B", "C"), "Pass", "Fail")
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.

data <- c(1, 2, NA, 4, NA, 6)
mean_value <- mean(data, na.rm = TRUE)
filled_data <- ifelse(is.na(data), mean_value, 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.

numbers <- c(1, 2, 3, 4, 5) 
parity <- ifelse(numbers %% 2 == 0, "Even", "Odd") 
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.

temperatures <- c(15, 8, 27, 12, 30, 9, 23, 5, 19)

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.

chars <- c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'o', 'p', 'u')

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.

scores <- c(45, 56, 67, 48, 90, 75, 33, 52)

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.

heights <- c(155, 162, 171, 185, 150, 178, 182, 165, 170)

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.

prices <- c(45, 150, 75, 30, 110, 60)

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.

scores <- c(85, 93, 67, 58, 72, 45)

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.

temperatures <- c(15, -2, 28, 8, 20, 32)