ยง2024-12-04
x <- 3
# check if x is greater than 0
if (x > 0) {
print("The number is positive")
}
age <- 15
# check if age is greater than 18
if (age > 18) {
print("You are eligible to vote.")
} else {
print("You cannot vote.")
}
x <- 20
# check if x is positive
if (x > 0) {
# check if x is even or odd
if (x %% 2 == 0) {
print("x is a positive even number")
} else {
print("x is a positive odd number")
}
# execute if x is not positive
} else {
# check if x is even or odd
if (x %% 2 == 0) {
print("x is a negative even number")
} else {
print("x is a negative odd number")
}
}
In R, the ifelse() function is a shorthand vectorized alternative to the standard if...else statement.
# A vector is the basic data structure in R that stores data of similar types.
# input vector
x <- c(12, 9, 23, 14, 20, 1, 5)
# ifelse() function to determine odd/even numbers
ifelse(x %% 2 == 0, "EVEN", "ODD")
# [1] "EVEN" "ODD" "ODD" "EVEN" "EVEN" "ODD" "ODD"
# input vector of marks
marks <- c(63, 58, 12, 99, 49, 39, 41, 2)
# ifelse() function to determine pass/fail
ifelse(marks < 40, "FAIL", "PASS")
# [1] "PASS" "PASS" "FAIL" "PASS" "PASS" "FAIL" "PASS" "FAIL"