很抱歉,这似乎是一个愚蠢的问题,但我想问一问,在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)
哪一天是数字,在转换情况下与字符匹配?
如果在switch()
中测试的表达式是数字,则大小写按位置匹配,因此可以省去参数名称并执行:
day = 2
weekday <- switch(day,
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Invalid Input!!")
print(weekday)
# Output:
# [1] "Monday"