Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

function
r
communitycreator

What is the ifelse() function in R?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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")
Implementing the ifelse() function

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.

RELATED TAGS

function
r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring