Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

I've found R's ifelse statements to be pretty handy from time to time. For example:

ifelse(TRUE,1,2)

# [1] 1

ifelse(FALSE,1,2)

# [1] 2

But I'm somewhat confused by the following behavior.

ifelse(TRUE,c(1,2),c(3,4))

# [1] 1

ifelse(FALSE,c(1,2),c(3,4))

# [1] 3

Is this a design choice that's above my paygrade?

1 Answer

0 votes
by

According to R Documentation:

ifelse {base}

Conditional Element Selection

Description

ifelse returns a value with the same shape as a test which is filled with elements selected from either yes or no depending on whether the element of the test is TRUE or FALSE.

Usage

ifelse(test, yes, no)

Arguments

test

an object which can be coerced to logical mode.

yes

return values for true elements of the test.

no

return values for false elements of the test.

  • Since you are passing test values of length 1, you are getting results of length 1. If you pass longer test vectors, you will get longer results.

For example:

ifelse(c(TRUE, FALSE), c(3,4), c(5, 6))

[1] 3 6

So ifelse is only used for the purpose of testing a vector of booleans and returning a vector of the same length, filled with elements taken from the vector’s yes and no arguments.

Related questions

Browse Categories

...