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
.
ifelse(test, yes, no)
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 the test
parameter.no
: This represents the return values for false elements of the test
parameter.# creating an objectx <- c(4, 2, 9, 3, 6)x# implemening the ifelse() functionifelse(x>5, "This is true", "This is false")
x
.x
.ifelse()
function to check if each element of x
is greater than 5
. The return value will be "This is true"
for each element greater than 5
and "This is false"
otherwise. We print the result to the console.