Control Structures in R
Control structures in R allow you to control the flow of your program. They include conditional statements (if-else, ifelse) and loops (for, while, repeat).
If-Else Statements
The if-else
statement is used to execute a block of code based on a condition.
age <- 20
if (age >= 18) {
print("You are an adult.")
} else {
print("You are a minor.")
}
Ifelse Function
The ifelse
function is a vectorized version of the if-else
statement.
ages <- c(15, 20, 25)
status <- ifelse(ages >= 18, "Adult", "Minor")
print(status)
Loops
Loops are used to execute a block of code repeatedly. R supports for
, while
, and repeat
loops.
# For Loop
for (i in 1:5) {
print(i)
}
# While Loop
count <- 0
while (count < 5) {
print(count)
count <- count + 1
}
# Repeat Loop
count <- 0
repeat {
print(count)
count <- count + 1
if (count >= 5) {
break
}
}
Break and Next Statements
The break
statement exits the loop, while the next
statement skips the current iteration.
# Break Example
for (i in 1:10) {
if (i == 5) {
break
}
print(i)
}
# Next Example
for (i in 1:10) {
if (i %% 2 == 0) {
next
}
print(i)
}
Vectorized Operations
R supports vectorized operations, which allow you to perform operations on entire vectors without explicit loops.
# Vectorized Addition
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
result <- v1 + v2
print(result)
Next: Functions