【发布时间】:2019-11-18 19:08:45
【问题描述】:
我对在 r 中编写函数还很陌生。我想出了一个示例函数。我正在寻求以下方面的帮助:
- 我有一个函数,其中包含可以作为特定选择之一的字符选择
- 我想检查该选项是否是该选项字符向量的一部分(与标题大小写无关)
- 如果可能的话,我还想使用
glue::glue,这样我的错误消息就可以更加具体。下面的例子。
如果字符向量中只允许一个选项,或者允许多个选项,你能告诉我编写错误的代码的区别吗?
library(stringr)
sample_function <- function(choice = c("apples", "bananas", "cherries")) {
allowed_choices <- c("apples", "bananas", "cherries")
# match to lowercase
choice <- str_to_lower(choice)
if(!choice %in% allowed_choices){
stop("Please choose Apples, Bananas, or Cherries")
}
}
sample_function(choice = "Test")
#> Error in sample_function(choice = "Test"): Please choose Apples, Bananas, or Cherries
Created on 2019-11-18 by the reprex package (v0.3.0)
我可以在停止消息中执行以下操作吗?我希望字符向量用逗号分隔:
glue::glue("{choice} is not a valid choice. Please choose from: {allowed_choices}")
【问题讨论】: