我想错误地捕获输入值以确保用户输入正确的选择.在这种情况下,有五个选项"ns","dl","sv","asv","cs".我想检查对这些的使用输入,如果这些都不存在然后返回和错误消息,如果空白默认为"ns"并向用户发送消息.我尝试扫描一个矢量字符串,但这不起作用.任何建议表示赞赏
method = "ns"
if(method != scan(c("ns", "dl", "sv", "asv" ))) {"Invalid Value"} else {method = method}
Run Code Online (Sandbox Code Playgroud)
A5C*_*2T1 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
Run Code Online (Sandbox Code Playgroud)
在不确切知道自己想做什么的情况下,您可能还需要查看该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
Run Code Online (Sandbox Code Playgroud)
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”
Run Code Online (Sandbox Code Playgroud)