如何使用整数表达式的switch语句?

时间:2017-07-01 16:03:33

标签: r switch-statement conditional rstudio

The below results in an error:
a = 3
switch(a,
       1 = {print(1)},
       2 = {print(2)},
       3 = {print(3)},
       {print("null")}
       )


> source('~/.active-rstudio-document', echo=TRUE)
Error in source("~/.active-rstudio-document", echo = TRUE) : 
  ~/.active-rstudio-document:3:10: unexpected '='
2: switch(a,
3:        1 =
            ^

为什么在上述情况下不能使用整数值?切换只适用于字符吗?

1 个答案:

答案 0 :(得分:1)

这是数字开关的正确语法:

switch(a,
   print(1),
   print(2),
   print(3),
)

如果a not in c(1:3),则会返回NULL