ifelse() function is a conditional statement that performs a certain operation based on a logical test. It allows you to check the conditions and perform operations on every element of a vector at once.
ifelse(Test, Yes, No)
- Test = logical condition
- Yes = return value if the logical condition is true
- No = return value if the logical condition is false
A student appeared for an exam in 5 different subjects and each subject has a passing mark of 33. The marks of each subject are stored in a variable as a vector. To determine if the student has passed or failed in each subject based on a condition, we will use the ifelse() function.
#vector of marks of each subject marks <- c(46, 78, 33, 15, 47, 31, 58, 9) #ifelse() function for evaluation ifelse(marks < 33, "FAIL", "PASS")
We can use ifelse() to check if the numbers in a vector are odd or even.
#vector of numbers numbers <- c(46, 78, 33, 15, 47, 31, 58, 9) #ifelse() function to check ODD/EVEN ifelse(numbers%%2==0, "EVEN", "ODD")