在R中选择案例中的案例

问题描述 投票:0回答:1

很抱歉,这似乎是一个愚蠢的问题,但我想问一问,在case中,switch case语句中的case是否必须始终是一个字符串?以下代码抛出错误:

day = 2
weekday <- switch(day,
                  1 = "Sunday",
                  2 = "Monday",
                  3 = "Tuesday",
                  4 = "Wednesday",
                  5 = "Thursday", 
                  6 = "Friday",
                  7 = "Saturday",
                  "Invalid Input!!")
print(weekday)

但是此代码非常有效:

day = 2
weekday <- switch(day,
                  '1' = "Sunday",
                  '2' = "Monday",
                  '3' = "Tuesday",
                  '4' = "Wednesday",
                  '5' = "Thursday", 
                  '6' = "Friday",
                  '7' = "Saturday",
                  "Invalid Input!!")
print(weekday)

哪一天是数字,在转换情况下与字符匹配?

r switch-statement
1个回答
0
投票

如果在switch()中测试的表达式是数字,则大小写按位置匹配,因此可以省去参数名称并执行:

day = 2
weekday <- switch(day,
                  "Sunday",
                  "Monday",
                  "Tuesday",
                  "Wednesday",
                  "Thursday", 
                  "Friday",
                  "Saturday",
                  "Invalid Input!!")
print(weekday)
# Output:
# [1] "Monday"
© www.soinside.com 2019 - 2024. All rights reserved.