【发布时间】:2021-09-27 10:27:28
【问题描述】:
我正在编写一个传入值向量的函数,并且我想在函数内使用这些值进行计算。但是,我也想使用我传递的向量的名称来返回有意义的错误消息,但不知道该怎么做。
我的函数是这样的
func <- function(vector, minimumvalue){
if(length(vector)==1){
return(1)}
else if (length(vector)<minimumvalue){
stop(paste0("The length of vector is less than ",minimumvalue))}
else if (length(vector)>minimumvalue){
stop(paste0("The length of vector is more than ",minimumvalue))}
else (return(vector))
}
我的函数调用如下所示
colours <- c("red","green","blue")
func(colours, 2)
一个返回
“向量的长度大于2”,但我想说“The 颜色长度大于 2"
我可以通过添加另一个参数来实现这一点,该参数将向量的名称作为字符串传递给函数,但我想知道是否有更好的设计方法。
【问题讨论】:
标签: r