R语言【技巧】——判断自定义函数的传参内容是否符合要求

1. 利用 if 条件判断,stop 语句报错

比如 对一个应该传入数值型,数值为 0 1 的参数:

if(add.strat<0 | add.strat>1){
    stop("add.strat represents the fraction of pseudoabsences that are
         sampled environmentally stratified and should be between 0 and 1!")
  }

比如 对一个应该传入字符型,字符串为 某个向量元素之一 的参数,类似于选项框:

possibtype=c("geographic","random","target.group","geo.strat","density",
               "env.strat","env.semi.strat")
  if(length(type)!=1 | !(type%in%possibtype)){
    stop("Invalid specification of pseudoabsence sampling type!")
  }

2. 利用 match.arg 语句判断传参是否在接收范围内

match.arg(value, choices = c("spatialvalid", "flagged", "clean"))

match.arg(centroids_detail, choices = c("both", "country", "provinces"))

match.arg(outliers_method, choices = c("distance", "quantile", "mad"))

你可能感兴趣的:(R语言,r语言,开发语言)