R switch statement on comparisons
Would cut()
do what you need?
Length <- 0:11
cuts <- c(-Inf, 1, 5, 10, Inf)
labs <- c("Walk", "bike", "drive", "fly")
as.character(cut(Length, breaks = cuts, labels = labs, include.lowest=TRUE))
# [1] "Walk" "Walk" "bike" "bike" "bike" "bike" "drive" "drive" "drive"
# [10] "drive" "drive" "fly"
Using dplyr's case_when
statement:
library(dplyr)
Length <- 3.5
mode <- case_when(
Length < 1 ~ "Walk",
1 <= Length & Length < 5 ~ "bike",
5 <= Length & Length < 10 ~ "drive",
Length >= 10 ~ "fly"
)
mode
#> [1] "bike"
Here is a similar answer to Josh's, but using findInterval
:
Length <- 0:11
cuts <- c(-Inf, 1, 5, 10, Inf)
labs <- c("Walk", "bike", "drive", "fly")
labs[findInterval(Length, cuts)]
# [1] "Walk" "bike" "bike" "bike" "bike" "drive" "drive"
# [8] "drive" "drive" "drive" "fly" "fly"
You can also use nested ifelse
statements, it's a matter of taste:
ifelse(Length < 1, "Walk",
ifelse(Length < 5, "bike",
ifelse(Length < 10, "drive",
"fly")))
# [1] "Walk" "bike" "bike" "bike" "bike" "drive" "drive"
# [8] "drive" "drive" "drive" "fly" "fly"
Cut and Switch: Use the factor level from cut() and pass into switch() to return appropriate code.
transport <- function(dist) {
stopifnot(is.numeric(dist))
x <- as.numeric(cut(dist, c(-Inf,0,1,5,10,Inf)), right = TRUE)
switch (x,
"No distance",
"Walk",
"Bike",
"Drive",
"Fly",
stop("Not sure")
)
}