关于比较的 R switch 语句 [英] R switch statement on comparisons

查看:20
本文介绍了关于比较的 R switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 R 脚本来根据在范围内拟合值来评估不同的表达式.这个想法是,如果 Length 在一个范围内,它将以一种方式进行评估,如果它在一个较长的范围内,它将以不同的方式进行评估.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆