ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

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

2026/8/7 19:33:22 拓冰建站 浏览量
R语言【技巧】——判断自定义函数的传参内容是否符合要求

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

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

if(add.strat<0 | add.strat>1){stop("add.strat represents the fraction of pseudoabsences that aresampled 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"))