- fast, but not vectorial
- must receive only one value, not a vector
- if returns a value which can be assigned
- always leave a space after
if
a <- if (one_logical_condition) value_when_TRUE else value_when_FALSE
- nested
if
s require curly brackets
if (one_logical_condition) {
# do something when condition is TRUE
} else {
# do something else when condition is FALSE
}
- vectorized version
- faster than
if
when dealing with a vector - treat it as a function
- as
if_else
but can deal with NAs and validates data types and vector lengths
- allow for different conditions
if (one_logical_condition) {
# do something when first condition is TRUE
} else if (second_logical_condition) {
# do something else when second condition is FALSE (and first is FALSE)
} else {
# do something when both conditions are FALSE
}
- think of it as multi-case
if
based on only one - one expression that evaluates to one number or one string
- good practice to have a catch-all case (first unnamed argument)
- think of it as vectorized
if
, with multiple conditions - uses formulas which must evaluate to a single value
- good practice to have a catch-all case
- think of it as multi-case
if_else
- uses formulas which must evaluate to a vector(!)
- good practice to have a catch-all case
Avoid row names in data frames
- Many functions in tidyverse remove them
- Not compatible with database tables
- other issues
- use
match.arg()
to validate function arguments