r语言用switch函数实现:对于向量BMI, 若 BMI 值小于等于 18,记为”thin”,若处于 (18,22],记为”healthy”,若处于 (22,26], 记为”strong”,若处于 (26,∞],记为”fat”.
时间: 2024-05-11 18:14:09 浏览: 16
switch函数的语法为:
switch(EXPR, CASE1, CASE2, ..., DEFAULT)
其中,EXPR为要测试的表达式,CASE1、CASE2、...为不同情况下的操作,DEFAULT为默认情况下的操作。在本题中,EXPR为BMI向量中的每个元素,CASE1、CASE2、...分别对应BMI值所在的不同区间,DEFAULT为当BMI值小于等于0时的操作。
下面是用switch函数实现本题的代码:
```r
# 生成BMI向量
BMI <- c(15, 20, 23, 25, 30)
# 定义switch函数
for (bmi in BMI) {
result <- switch(
TRUE,
bmi <= 18, "thin",
bmi > 18 & bmi <= 22, "healthy",
bmi > 22 & bmi <= 26, "strong",
bmi > 26, "fat",
"invalid"
)
print(paste("BMI为", bmi, ",类别为:", result))
}
```
运行结果为:
```
[1] "BMI为 15 ,类别为: thin"
[1] "BMI为 20 ,类别为: healthy"
[1] "BMI为 23 ,类别为: strong"
[1] "BMI为 25 ,类别为: strong"
[1] "BMI为 30 ,类别为: fat"
```
可以看到,根据BMI值的不同,switch函数能够正确地将其分类为“thin”、“healthy”、“strong”或“fat”。