gpt4 book ai didi

r - 验证 R 中函数的输入

转载 作者:行者123 更新时间:2023-12-04 10:52:20 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于r - 验证 R 中函数的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19363827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com