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 the test parameter.
  • no: This represents the return values for false elements of the test parameter.

Example

# creating an object
x <- c(4, 2, 9, 3, 6)
x
# implemening the ifelse() function
ifelse(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 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.

Free Resources