关于比较的R switch语句 [英] R switch statement on comparisons
问题描述
我正在尝试编写一个R脚本来根据范围内的值拟合来评估不同的表达式。我们的想法是,如果长度在一个范围内,它将以一种方式进行评估,如果它在更长的范围内,它将以不同的方式进行评估。
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.
我可以使用if / else语句来完成这项工作,但它非常难看,而且我确信必须有更好的方法......这里的代码可行。
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"
我一直在尝试使用switch函数进行一些工作,但它似乎只适用于文本或整数...有没有办法让switch语句在每种情况下进行评估?
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"
)
推荐答案
以下是Josh的类似答案,但使用 findInterval
:
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"
您还可以使用嵌套的 ifelse
语句,这是一个品味问题:
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"
这篇关于关于比较的R switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!