Loops and Conditional Statements in R

Explore practical examples of using loops and conditional statements in R programming.
By Taylor

Understanding Loops and Conditional Statements in R

Loops and conditional statements are fundamental concepts in programming that help automate repetitive tasks and make decisions based on certain conditions. In R, these tools can simplify complex operations and enhance your coding efficiency. Below are three diverse examples of using loops and conditional statements in R, each with a specific context to help you understand their applications better.

Example 1: Summing Even Numbers in a Vector

Context

In this example, we will create a function that sums all even numbers from a given vector. This is a common task when dealing with numerical data.

sum_even_numbers <- function(numbers) {
  total <- 0  # Initialize total to 0
  for (num in numbers) {  # Loop through each number in the vector
    if (num %% 2 == 0) {  # Check if the number is even
      total <- total + num  # Add it to total if it is even
    }
  }
  return(total)  # Return the final sum
}

# Example usage:
numbers_vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
result <- sum_even_numbers(numbers_vector)
print(result)  # Output will be 30

Notes

  • The %% operator checks for even numbers by finding the remainder when divided by 2.
  • You can modify the function to sum odd numbers by changing the condition to num %% 2 != 0.

Example 2: Grade Classification Based on Score

Context

This example demonstrates how to classify students’ grades based on their scores using conditional statements. It’s useful in educational software.

classify_grade <- function(scores) {
  grades <- c()  # Initialize an empty vector for grades
  for (score in scores) {  # Loop through each score
    if (score >= 90) {
      grades <- c(grades, 'A')  # Assign 'A' for scores 90 and above
    } else if (score >= 80) {
      grades <- c(grades, 'B')  # Assign 'B' for scores between 80 and 89
    } else if (score >= 70) {
      grades <- c(grades, 'C')  # Assign 'C' for scores between 70 and 79
    } else if (score >= 60) {
      grades <- c(grades, 'D')  # Assign 'D' for scores between 60 and 69
    } else {
      grades <- c(grades, 'F')  # Assign 'F' for scores below 60
    }
  }
  return(grades)  # Return the vector of grades
}

# Example usage:
scores_vector <- c(95, 85, 76, 54, 89, 100)
grades_result <- classify_grade(scores_vector)
print(grades_result)  # Output will be A B C F B A

Notes

  • This function can easily be adapted for different grading systems by adjusting the score ranges.
  • You can extend the function to also return comments like ‘Excellent’, ‘Good’, etc., based on the grade.

Example 3: Filtering Out Negative Numbers

Context

In this example, we will filter out negative numbers from a list and return only the non-negative numbers. This is beneficial in data cleaning tasks.

filter_negative_numbers <- function(numbers) {
  non_negative <- c()  # Initialize an empty vector for non-negative numbers
  for (num in numbers) {  # Loop through each number in the input vector
    if (num >= 0) {  # Check if the number is non-negative
      non_negative <- c(non_negative, num)  # Add it to the non-negative vector
    }
  }
  return(non_negative)  # Return the filtered vector
}

# Example usage:
numbers_vector <- c(-5, 3, -1, 7, 0, -12, 8)
filtered_numbers <- filter_negative_numbers(numbers_vector)
print(filtered_numbers)  # Output will be 3 7 0 8

Notes

  • This function can be modified to return only the negative numbers by changing the condition to num < 0.
  • You can also implement this functionality using the Filter() function in R for a more compact solution.

These examples illustrate how loops and conditional statements can be effectively utilized in R programming. By understanding these core concepts, you can handle a variety of tasks in your coding projects with ease!