Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check existence of an input argument for R functions

I have a function defined as

myFun <- function(x, y, ...) {   # using exists   if (exists("z")) { print("exists z!") }   # using missing   try(if (!missing("z")) { print("z is not missing!") }, silent = TRUE)   # using get   try(if (get("z")) { print("get z!") }, silent = TRUE)    # anotherFun(...) } 

In this function, I want to check whether user input "z" in the argument list. How can I do that? I tried exists("z"), missing("z"), and get("z") and none of them works.

like image 354
danioyuan Avatar asked Mar 26 '12 18:03

danioyuan


People also ask

How do you find an argument in a function in R?

Get the List of Arguments of a Function in R Programming – args() Function. args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.

Can an R function have no arguments?

Functions are defined using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class “function”. Here's a simple function that takes no arguments and does nothing.

Does a function need an argument in R?

An R function is a packaged recipe that converts one or more inputs (called arguments) into a single output. The recipe is implemented as a single R expression that uses the values of the arguments to compute the result.

What type of arguments can a function take in R?

Arguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R.


1 Answers

I think you're simply looking for hasArg

myFun <- function(x, y, ...) {    hasArg(z) }  > myFun(x=3, z=NULL) [1] TRUE 

From ?hasArg:

The expression hasArg(x), for example, is similar to !missing(x), with two exceptions. First, hasArg will look for an argument named x in the call if x is not a formal argument to the calling function, but ... is. Second, hasArg never generates an error if given a name as an argument, whereas missing(x) generates an error if x is not a formal argument.

like image 73
GSee Avatar answered Oct 07 '22 06:10

GSee