7

我想错误捕获输入值以确保用户输入正确的选择。在这种情况下,有五个选项“ns”、“dl”、“sv”、“asv”、“cs”。如果这些都不存在,我想检查这些使用输入,然后返回并错误消息,如果空白默认为“ns”并向用户发送消息。我尝试扫描矢量字符串,但没有奏效。任何建议表示赞赏

   method = "ns"
   if(method != scan(c("ns", "dl", "sv", "asv" ))) {"Invalid Value"} else {method = method}  
4

1 回答 1

12

您可能正在寻找%in%,并且可以按照以下方式使用它:

myFun <- function(input=NULL) {
  Check <- c("ns", "dl", "sv", "asv", "cs")
  if (is.null(input)) {
    message("No 'input' value defined. Using 'ns' by default")
    input <- "ns"
  } 
  if (!input %in% Check) stop("Invalid 'input' value")
  input
}

myFun()
# No 'input' value defined. Using 'ns' by default
# [1] "ns"
myFun("sv")
# [1] "sv"
myFun("vs")
# Error in myFun("vs") : Invalid 'input' value

在不确切知道您想要做什么的情况下,您可能还想查看该switch功能。

myFun2 <- function(input = NULL) {
  Check <- c("ns", "dl", "sv", "asv", "cs")
  if (is.null(input)) {
    message("No 'input' value defined. Using 'ns' by default")
    input <- "ns"
  } 
  switch(input,
         ns = "Whoo",
         dl = "Whee",
         sv = "Whaa",
         asv = "Whii",
         cs = "Whuu",
         stop("You did not say the magic word"))
}

myFun2()
# No 'input' value defined. Using 'ns' by default
# [1] "Whoo"
myFun2("sv")
# [1] "Whaa"
myFun2("sc")
# Error in myFun2("sc") : You did not say the magic word

更新:match.arg

根据大众的需求,这里match.arg也是上述的一个版本,但请注意,您不再需要输入关于不使用魔法词的消息,而是必须使用自动生成的描述性和有用的错误消息来解决。这不好玩....

myFun3 <- function(input=NULL) {
  Check <- c("ns", "dl", "sv", "asv", "cs")
  if (is.null(input)) {
    message("No 'input' value defined. Using 'ns' by default")
    input <- "ns"
  } 
  input <- match.arg(input, Check)
  switch(input,
         ns = "Whoo",
         dl = "Whee",
         sv = "Whaa",
         asv = "Whii",
         cs = "Whuu")
}

myFun3()
# No 'input' value defined. Using 'ns' by default
# [1] "Whoo"
myFun3("sv")
# [1] "Whaa"
myFun3("sc")
# Error in match.arg(input, Check) : 
#   'arg' should be one of “ns”, “dl”, “sv”, “asv”, “cs”
于 2013-10-14T15:41:09.393 回答