R语言函数如何获取传入vector参数的变量名以优化报错信息
实现方法
不需要额外新增专传变量名的参数,使用R内置的substitute()捕获函数调用时传入参数的原始表达式,再通过deparse()将表达式转为字符串,即可直接获取传入的变量名。
修改后的函数代码如下:
func <- function(vector, minimumvalue){ # 提取传入参数的变量名 vec_name <- deparse(substitute(vector)) if(length(vector) == 1){ return(1) } else if (length(vector) < minimumvalue){ stop(paste0("The length of ", vec_name, " is less than ", minimumvalue)) } else if (length(vector) > minimumvalue){ stop(paste0("The length of ", vec_name, " is more than ", minimumvalue)) } else { return(vector) } }
调用测试:
colours <- c("red","green","blue") func(colours, 2)
运行后输出的报错完全符合预期:
Error in func(colours, 2) : The length of colours is more than 2
补充说明
如果调用时直接传入表达式而非已赋值的变量(例如func(c("a","b","c"), 2)),报错会自动识别为表达式内容,输出The length of c("a", "b", "c") is more than 2,可读性也符合要求,无需额外适配。
内容的提问来源于stack exchange,提问作者z star
相关产品推荐
相关产品推荐

