Francis Smart
Francis Smart

Reputation: 4055

If else operator

Could someone please just tell me the switch in R that returns the second argument if true and the third if false?

I have searched for switch and if else function and I have looked through the documentation but when using ubiquitous terms like if and else it seems very hard to identify a solution.

I am looking for something like:

f(TRUE,1,2); f(FALSE,1,2)
[1] 1
[1] 2

I am working on reading through the documentation of Julia which has made me aware of some of my gaps in knowledge in R. In Julia there is an operator available.

(true  ? 1 : 2) 
1
(false ? 1 : 2)
2

Upvotes: 0

Views: 201

Answers (2)

bartektartanus
bartektartanus

Reputation: 16080

Simply ifelse

ifelse(TRUE,1,2)
## [1] 1
ifelse(FALSE,1,2)
## [1] 2

Upvotes: 4

Dirk is no longer here
Dirk is no longer here

Reputation: 368191

Try this

 ifelse(condition, 1, 2)

Oddly enough, it is named ifelse() :-)

PS And while we're at it, do not use T and F, use TRUE and FALSE. Every self-respecting style-guide suggests so.

Upvotes: 6

Related Questions