在R中使用switch()
,如果EXPR
的输入未在switch
语句中定义,我如何能错误地中止?
以animal_sound()
为例。它接受一个动物的名字并返回该动物发出的声音。
animal_sound <- function(x) {
switch(x,
"dog" = "woof",
"cat" = "meow",
"bee" = "bzzz",
"duck" = "quack")
}
只要动物是在switch()
中定义的,就可以。
animal_sound("bee")
#> [1] "bzzz"
animal_sound("cat")
#> [1] "meow"
但是如果传递一个没有定义的动物,则返回值为空白(甚至不包括NULL
)。
animal_sound("alligator")
## nothing is printed to console
是否有一种方法可以抛出错误或设置默认返回值,如果输入没有匹配?
我本可以对执行以下操作,这是一个不希望的解决方案:
animal_sound_with_error_message <- function(x) {
valid_input_animals <- c("dog", "cat", "bee", "duck")
input_is_valid <- any(x %in% valid_input_animals)
if (!input_is_valid) {
stop("animal is not supported. Try a different animal.")
}
switch(x,
"dog" = "woof",
"cat" = "meow",
"bee" = "bzzz",
"duck" = "quack")
}
animal_sound_with_error_message("bee")
#> [1] "bzzz"
animal_sound_with_error_message("cat")
#> [1] "meow"
animal_sound_with_error_message("alligator")
#> Error in animal_sound_with_error_message("alligator"): animal is not supported. Try a different animal.
由reprex包(v0.3.0)于2018-10-18创建
我不喜欢这个解决方案,因为它需要在开始时手动定义所有可能的输入。这既愚蠢(考虑到我们稍后在switch()
中定义相同的内容),又容易出错,如果我稍后向switch
添加更多输入,并且可能忘记更新valid_input
向量。
在不支持输入的情况下,是否有一种优雅/简洁的方法来返回信息错误消息?
您可以添加这样的默认值。
animal_sound <- function(x) {
switch(x,
"dog" = "woof",
"cat" = "meow",
"bee" = "bzzz",
"duck" = "quack",
"default")
}
您可以使用match.arg()
函数检查参数。这将生成一个适当的错误消息。
它不容易出错,但在这种情况下,这是一个很好的实践,因为参数可以在{Roxygen}
中使用。
animal_sound_with_error_message <- function(x = c("dog", "cat", "bee", "duck")) {
match.arg(x)
switch(x,
"dog" = "woof",
"cat" = "meow",
"bee" = "bzzz",
"duck" = "quack")
}
根据@Norie的回答和@Roland的评论,我做了进一步的修改。
animal_sound <- function(x) {
my_error <- rlang::abort(paste(x, "isnt supported", sep = " "))
switch(x,
"dog" = "woof",
"cat" = "meow",
"bee" = "bzzz",
"duck" = "quack",
my_error)
}
animal_sound("crocodile")
#> Error: crocodile isnt supported
由reprex包(v0.3.0)于2018-10-18创建