Conditionals in R
Branching, and its vectorized alternative.
grade <- function(score) {
if (score >= 90) {
"A"
} else if (score >= 80) {
"B"
} else {
"F"
}
}
marks <- sapply(c(95, 85, 40), grade)
vectorized <- ifelse(c(95, 85, 40) >= 80, "pass", "fail")
How it works
- An
if/else ifchain returns the matching branch. sapplyapplies the function across a vector.ifelseis the vectorized form, testing every element.
Keywords and builtins used here
celsefunctionififelsesapply
The run, in numbers
- Lines
- 12
- Characters to type
- 193
- Tokens
- 70
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 49 seconds.
Step 1 of 5 in Flow & functions, step 5 of 20 in Language basics.