Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an argument of a function is set or not in R

I have a function f that takes two parameters (p1 and p2):

If for the parameter p2 no value was passed to the function, the value of p1^2 should be used instead. But how can I find out within the function, if a value is given or not. The problem is that the variable p2 is not initialized if there was no value. Thus I can't test for p2 being NULL.

f <- function(p1, p2) {     if(is.null(p2)) {         p2=p1^2     }     p1-p2 } 

Is it somehow possible to check if a value for p2 was passed to the function or not? (I could not find an isset() - function or similar things.)

like image 789
R_User Avatar asked Nov 01 '11 09:11

R_User


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.

What is argument matching in R?

14.3 Argument Matching rm is a logical indicating whether missing values should be removed or not.

Is parameter and argument are same?

Note the difference between parameters and arguments: Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.

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

You use the function missing() for that.

f <- function(p1, p2) {     if(missing(p2)) {         p2=p1^2     }     p1-p2 } 

Alternatively, you can set the value of p2 to NULL by default. I sometimes prefer that solution, as it allows for passing arguments to nested functions.

f <- function(p1, p2=NULL) {     if(is.null(p2)) {         p2=p1^2     }     p1-p2 }  f.wrapper <-function(p1,p2=NULL){     p1 <- 2*p1     f(p1,p2) } > f.wrapper(1) [1] -2 > f.wrapper(1,3) [1] -1 

EDIT: you could do this technically with missing() as well, but then you would have to include a missing() statement in f.wrapper as well.

like image 174
Joris Meys Avatar answered Oct 06 '22 03:10

Joris Meys