if (condition) {
// code block
}This block runs only if the condition inside the if is TRUE.
x <- 7
if (x > 5) {
print("x is greater than 5")
}x <- 3
if (x > 5) {
print("Greater than 5")
} else {
print("Not greater than 5")
}Use else to specify an alternative action.
Use multiple else if blocks to test a sequence of conditions.
x <- 5
if (x > 10) {
print("x > 10")
} else if (x == 5) {
print("x is exactly 5")
} else {
print("x is something else")
}Nesting allows handling compound logic, but can reduce readability if overused.
x <- 10
if (x > 5) {
if (x %% 2 == 0) {
print("x is even and > 5")
}
}ifelse() applies the condition across all elements in the vector.
ages <- c(15, 22, 17, 30)
status <- ifelse(ages >= 18, "Adult", "Minor")
print(status){} consistently for blocks, even if optionalifelse() over loops for element-wise logicAsk the AI if you need help understanding or want to dive deeper in any topic