验证R中函数的输入

时间:2013-10-14 15:33:26

标签: r

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

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

1 个答案:

答案 0 :(得分:11)

您可能正在寻找%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”