R ifelse()

Here, we are going to have a look at the method "ifelse()" provided by R language.

We'll cover the following

Most of the programs written in R language involve some kind of manipulation of vectors. Vectors are basic R Objects.

Use of ifelse() Function

Now, imagine a case where we have to write if...else statement for each element present in a vector. This task can be easily and efficiently coded using ifelse(). It is the vector equivalent form of the if…else statement in R.

Syntax

ifelse(expression, condition1, condition2)

# Here "expression" is an object which can be coerced to logical mode.
# Condition1 is returned for elements that satisfy the expression (return TRUE)
# Condition2 is returned for elements that do not satisfy the expression (return FALSE)

The output of ifelse() function is always a vector! Each element of the output vector tells whether the test (expression) passed for that element of the input vector.

Let’s revisit our original positive and negative numbers problem using vectors this time.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy