我正在尝试创建一个输入很少的函数。我想知道如何检查我的论点的可用性。这是我的功能:
MyFunction<-function(data,window,dim,option) {
}
首先,我想查看是否有任何参数,如果没有,则打印错误 是否正确使用
if ~nargin
error('no input data')
}
然后,我想确保第二个参数也插入了 这样问是不对的
if nargin < 2
error('no window size specified')
}
然后,我想检查第三个参数是否为空,将其设置为1
if nargin < 3 || isempty(dim)
dim<-1
}
答案 0 :(得分:3)
您可以使用hasArg()
testfunction <- function(x,y){
if(!hasArg(x)){
stop("missing x")
}
if(!hasArg(y)){
y = 3
}
return(x+y)
}
>testfunction(y=2)
Error in testfunction(y = 2) : missing x
> testfunction(x=1,y=2)
[1] 3
> testfunction(x=1)
[1] 4
答案 1 :(得分:1)
正如@Ben Bolker所说,缺失用于测试值是否被指定为函数的参数。您可以在R功能中使用不同的条件,例如警告或停止。 在你的情况下,我会做以下
MyFunction<-function(data,window,dim,option) {
if (missing(data))
stop("the first argument called data is missing")
if (missing(window))
stop("the second argument called window is missing")
if (missing(dim))
dim <- 1
if (missing(option))
stop("the second argument called option is missing")
}