r - 输入错误时函数不会引发错误
问题描述
它适用于ListPalette()
和ListPalette("PunjabiPalette")
如果我传入不正确的值,而不是显示错误并终止函数,它会继续并显示调色板。
我也试过listname != "PunjabiPalette"
了!identical(listname,"PunjabiPalette")
如果参数不正确,如何正确显示错误?
ListPalette <- function(listname){
if (is.null(names(args))){
listname <- "PunjabiPalette"
}
else if (!(args %in% "PunjabiPalette")){
stop(paste0(listname, " does not exist."))
}
list <- get(listname)
names(list)
}
解决方案
args()
是一个默认函数,可以获取已定义函数的参数,它不允许您访问函数定义中的参数。所以你的方法是行不通的。
您的第一if
条语句不是必需的,您可以通过=
在函数定义中包含它们来指定 R 中的默认参数。要停止无效输入,使用listname != "PunjabiPalette"
对我来说很好,如下所示。该函数在不是"PunjabiPalette"
. 我还假设您已将其定义为全局环境中的列表,使用get
. 我不推荐这种做法(尝试制作一个列表列表),但这应该暂时有效。
PunjabiPalette <- list("a" = 1, "b" = 2) # example list with named elements
ListPalette <- function(listname = "PunjabiPalette"){
if (listname != "PunjabiPalette"){
stop(paste0(listname, " does not exist."))
}
list <- get(listname)
names(list)
}
print(ListPalette()) # works with missing argument
#> [1] "a" "b"
print(ListPalette("PunjabiPalette")) # works with valid argument
#> [1] "a" "b"
print(ListPalette("OtherName")) # fails with incorrect argument
#> Error in ListPalette("OtherName"): OtherName does not exist.
由reprex 包(v0.2.0)于 2018-05-30 创建。
推荐阅读
- java - 使用 java.lang.ThreadLocal 有什么一般的缺点吗?
- mongodb - MongoDB服务器白名单
- laravel - 如何在laravel上切换语言按钮
- spring - Spring批量JDBC批量写入如何处理SQL异常
- html - 进度条重复百分比
- html - 从 url 的下拉列表中选择一个选项
- javascript - API Gateway JavaScript SDK 超时
- go - 如何将 []int 转换为 [2]int?
- java - 如何将 Java jar 包含到 C# Xamarin 项目(毕加索示例),ImageView android:src 字段的问题
- python - music21 show('midi') 只播放一个乐谱部分