I'm trying to write an R script to evaluate different expressions based on fitting a value within ranges. The idea is that if Length is within one range, it will get evaluated one way, and if it's in a longer range it will get evaluated differently.
I can make this work with if/else statements, but it's pretty ugly, and I'm sure there must be a better way... here's code that works.
Length=8.2
if (Length<1)
mode="Walk"
else if (1<=Length & Length <5)
mode="bike"
else if (5<=Length & Length <10)
mode="drive"
else if (Length>=10)
mode="fly"
I've been trying to make something work with the switch function, but it seems to only work with text or integers... is there a way to have a switch statement that conducts evaluations at each case such as this?
Length=3.5
switch(Length,
(Length<1) mode="Walk"
(1<=Length & Length <5) mode="bike"
(5<=Length & Length <10) mode="drive"
(Length=>10) mode="fly"
)
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"
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With