Loops and Conditional Statements

Loops and conditional statements are fundamental programming constructs in R that allow you to control the flow of your code, repeat tasks, and make decisions based on conditions.

1. Conditional Statements

Conditional statements allow your code to take different actions depending on whether a condition is TRUE or FALSE.

a) if Statement

x <- 10if (x > 5) {
print("x is greater than 5")
}

b) if-else Statement

x <- 3if (x > 5) {
print("x is greater than 5")
} else {
print("x is 5 or less")
}

c) if-else if-else Statement

x <- 7if (x > 10) {
print("x is greater than 10")
} else if (x > 5) {
print("x is between 6 and 10")
} else {
print("x is 5 or less")
}

2. Loops in R

Loops allow you to repeat a block of code multiple times.

a) for Loop

Used to iterate over a sequence or vector:

for (i in 1:5) {
print(paste("Iteration", i))
}

Looping through a vector:

names <- c("Alice", "Bob", "Charlie")for (name in names) {
print(paste("Hello", name))
}

b) while Loop

Repeats a block of code as long as a condition is TRUE:

count <- 1while (count <= 5) {
print(paste("Count is", count))
count <- count + 1
}

c) repeat Loop

Repeats code indefinitely until a break condition is met:

count <- 1repeat {
print(paste("Count is", count))
count <- count + 1
if (count > 5) {
break
}
}

3. Combining Loops and Conditional Statements

You can use conditional statements inside loops for more control:

numbers <- c(1, 3, 5, 6, 8)for (num in numbers) {
if (num %% 2 == 0) {
print(paste(num, "is even"))
} else {
print(paste(num, "is odd"))
}
}

4. Advantages of Using Loops and Conditionals

  • Automate repetitive tasks efficiently
  • Make programs dynamic and flexible
  • Allow decision-making based on conditions
  • Essential for data processing, simulations, and iterative calculations

Conclusion

Loops and conditional statements are essential tools in R programming. They allow you to automate repetitive tasks, perform calculations dynamically, and control the flow of your code based on conditions. Mastering these constructs is a key step toward becoming a proficient R programmer.

Home ยป R Programming (R Lang) > Programming in R > Loops and Conditional Statements