Bonjour!
In our daily life, we often face a condition where we have to anticipate and prepare for more than one outcome that might happen as a result of something that we have done. In a programming world, this situation is called a conditional statement. In R, there are two ways of how we can handle conditional statement: if-else
and case-when
.
A. if-else
if-else
can be done in two different ways: using if-else
statement and ifelse()
function.
- if-else statement
12345if (test_expression) {statement1} else {statement2}
Example:
12345if(x > 75){print("pass")} else {print("fail")} ifelse()
function
Usage: ifelse(test_expression, x, y)
Example:
123> x = c(75,17,92,39)> ifelse(x > 75,"pass","fail")[1] "fail" "fail" "pass" "fail"
If we want to do nothing with the else
part, we can do something like:
ifelse(is.na(donors$age), summary(donors$age)['Mean'], donors$age)
B. case_when()
Can we have too many conditions that we have to anticipate, it’s less painful to use case_when()
.
Usage: case_when(cond1 ~ do1, cond2 ~ do2, ....)
Example:
1 2 3 4 5 6 |
+ case_when( + substr(prov, 1, 1) == 1 ~ "sumatera", + substr(prov, 1, 1) == 3 ~ "jawa", + substr(prov, 1, 1) == 6 ~ "kalimantan", + substr(prov, 1, 1) == 7 ~ "sulawesi" + ) |
Well, that’s my post for this week. It’s short but hopefully useful.
See you in my next post.
Cheers,