1
2
3
4
5
#

R: if, if-else, and ifelse functions


I. Introduction

if, if-else, and ifelse functions are extremely powerful, and useful, in programming. In general, they allow a condition or collection of conditions to be checked, and depending on the result, certain code can then be run or not run.


II. if function

The if function uses the following general format: if(condition) {code}

The if function works by testing a condition. If the condition is true, the code is run. If the condition is false, the code is not run. 

Example

> x = 10
> y = 1
>
> # CONDITION IS FALSE
> if(x > 10) {y = 2}
> y
[1] 1
> 
> # CONDITION IS TRUE
> if(x == 10) {y = 4}
> y
[1] 4

II. if-else function

The if-else function uses the following general format: if(condition) {code1} else {code2}

The if-else function works by testing a condition. If the condition is true, the code1 is run. If the condition is false, the code2 is run. 

Example

> a = 1
> b = 1
> 
> # CONDITION IS TRUE
> if(a == 1) {b = 2} else {b = 3}
> b
[1] 2
> 
> # CONDITION IS FALSE
> if(a != 1) {b = 2} else {b = 3}
> b
[1] 3

III. ifelse function

The ifelse function uses the following general format: ifelse(condition, true.value, false.value)

The ifelse function works by testing a condition. If the condition is true, true.value is returned. If the condition is false, then false.value is returned. 

Example

> x = 1
> 
> # CONDITION TRUE
> ifelse(x == 1,  2, 4)
[1] 2
> 
> # CONDITION FALSE
> ifelse(x > 1,  2, 4)
[1] 4

 

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.