首页 > 解决方案 > 输入错误时函数不会引发错误

问题描述

这是我在 GitHub存储库中的脚本

它适用于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)
}

标签: rstringcompare

解决方案


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 创建。


推荐阅读