a <- 5
if (a > 3){
print("a is bigger than 3")
}[1] "a is bigger than 3"
if
if...else and else if
ifelse()
Basic syntax:
if (condition){
# do task
}Example:
a <- 5
if (a > 3){
print("a is bigger than 3")
}[1] "a is bigger than 3"
The code inside the braces runs only if the condition is TRUE.
Use else to define what happens when the condition is FALSE.
[1] "a is bigger than 3"
Only one block will execute.
Use else if to test multiple conditions.
[1] "a is bigger than 3"
R checks conditions from top to bottom and stops when one is TRUE.
ifelse() Functionifelse() is a vectorized version of if.
Syntax:
ifelse(condition, value_if_true, value_if_false)Example:
a <- 5
ifelse(a > 3,
"a is bigger than 3",
"a is not bigger than 3")[1] "a is bigger than 3"
Unlike if, ifelse() works well on vectors:
x <- 1:5
ifelse(x > 3, "big", "small")[1] "small" "small" "small" "big" "big"
Use ifelse() when working with vectors or data frame columns.