【问题标题】:how to use switch statements with integer expression?如何使用带有整数表达式的 switch 语句?
【发布时间】:2017-07-01 16:03:33
【问题描述】:
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 =
            ^

为什么在上述情况下不能使用整数值? switch 只对字符有效吗?

【问题讨论】:

  • 并不是不能使用整数。 switch 语句的语法错误。请输入?switch 并阅读文档。

标签: r switch-statement conditional rstudio


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多