nik
nik

Reputation: 2584

Check each argument exists as an input in a function

I am trying to make a function which gets few inputs. I would like to know how to check the availability of my arguments . Here is my function:

MyFunction<-function(data,window,dim,option) {

}

First, I want to see if there is any argument , if no, print an error is it correct to use

if ~nargin
    error('no input data')
   }

Then, I want to make sure that the second argument is also inserted
is it right to ask like this

if nargin < 2
    error('no window size specified')
   }

Then, I want to check if the third argument is empty , set it as 1

if nargin < 3 || isempty(dim)
    dim<-1
   }

Upvotes: 2

Views: 226

Answers (2)

user5947301
user5947301

Reputation:

As @Ben Bolker said , missing is used to test whether a value was specified as an argument to a function. You can have different conditions in your R functions such as warning or stop. In your case, I would do the following

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")
}

Upvotes: 1

zacdav
zacdav

Reputation: 4671

you can use 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

Upvotes: 3

Related Questions