What is the ifelse() function in R?
Overview
The ifelse() function in R is a conditional element selection function that returns a value that has the same shape as the test parameter. This has elements that are selected from either yes or no parameters and depends on whether the element of the test parameter is TRUE or FALSE.
Syntax
ifelse(test, yes, no)
Parameter value
The ifelse() function takes the following parameter values:
test: This represents the object that can be forced to a logical mode.yes: This represents the return values for true elements of thetestparameter.no: This represents the return values for false elements of thetestparameter.
Example
# creating an objectx <- c(4, 2, 9, 3, 6)x# implemening the ifelse() functionifelse(x>5, "This is true", "This is false")
Explanation
- Line 2: We create a variable
x. - Line 4: We print the variable
x. - Line 6: We implement the
ifelse()function to check if each element ofxis greater than5. The return value will be"This is true"for each element greater than5and"This is false"otherwise. We print the result to the console.