R: Find the variables included in the function with the argument "...", exists ()

I want to provide an optional function variable, let the functions check if this argument has been provided, and let it perform the corresponding set of calculations. I thought I could use the "..." operator for this.

The simplest example I can come up with (which, unfortunately, failed) is this:

monkeyfun = function(...){ if (exists("monkey")){ return('monkey found') } else { return('monkey not found') } } 

Now monkeyfun(monkey=0) as well as monkeyfun() returning "monkey not found" .

As a health check, the definition of monkey = 1 outside the function works and returns "monkey found" .

The documentation for the argument '...' does not really help me understand this problem, and I could not find the wording of this question that gives the corresponding results here (I understand that this question is the main one and most likely is being discussed somewhere ) ...

I would really appreciate help on this.

+6
source share
4 answers

I would use hasArg :

 monkeyfun <- function(...) { if (hasArg("monkey")) { return('monkey found') } else { return('monkey not found') } } monkeyfun() # [1] "monkey not found" monkeyfun(monkey=0) # [1] "monkey found" 
+5
source

I would use match.call , since it returns all the function arguments given by their full names. Here's How I would rewrite your function:

 monkeyfun = function(...){ params <- as.list(match.call()[-1]) if ("monkey" %in% names(params)){ ## note how I change the test here return('monkey found') } else { return('monkey not found') } } # monkeyfun() # [1] "monkey not found" # > monkeyfun(monkey=0) # [1] "monkey found" 
+4
source

Take a look at this dialog box with the interpreter R. Normally, existence is tested if the length is greater than 0:

  monkeyfun = function(...){ print(str(list(...))) } monkeyfun(monkey=0) #List of 1 # $ monkey: num 0 #NULL monkeyfun = function(...){ loclist = list(...) if (exists(loclist$monkey)){ return('monkey found') } else { return('monkey not found') } } monkeyfun(monkey=0) #Error in exists(loclist$monkey) : invalid first argument monkeyfun = function(...){ loclist = list(...) if (length(loclist$monkey)){ return('monkey found') } else { return('monkey not found') } } monkeyfun(monkey=0) #[1] "monkey found" monkeyfun(monk_uncle=1) #[1] "monkey not found" 
+3
source

This is due to how the non-standard assessment works in R ( http://adv-r.had.co.nz/Computing-on-the-language.html#capturing-dots ). You can print the list of objects passed to the function using ... with print(list(...)) , you can evaluate them with eval(substitute(alist(...))) . In your case, you want to check if the object is defined in ... This can be done using the following code.

  monkeyfun = function(...){ print(list(...)) if ("monkey"%in%names(list(...))){ return('monkey found') } else { return('monkey not found') } } 
+1
source

Source: https://habr.com/ru/post/983485/


All Articles