[R] Testing for arguments in a function

David Winsemius dwinsemius at comcast.net
Mon Sep 26 23:15:53 CEST 2011


On Sep 26, 2011, at 4:56 PM, Duncan Murdoch wrote:

> On 26/09/2011 3:39 PM, Gene Leynes wrote:
>> I don't understand how this function can subset by i when i is  
>> missing....
>>
>> ## My function:
>> myfun = function(vec, i){
>>     ret = vec[i]
>>     ret
>> }
>>
>> ## My data:
>> i = 10
>> vec = 1:100
>>
>> ## Expected input and behavior:
>> myfun(vec, i)
>>
>> ## Missing an argument, but error is not caught!
>> ## How is subsetting even possible here???
>> myfun(vec)
>
> Subsetting allows missing arguments.  What you have is equivalent to  
> evaluating
>
> vec[]
>
> which is legal.

But I don't think "vec[]" is what he is seeing. At least it's not what  
I see. I see 10 coming back. I assumed it was simply because "i" was  
not found inside the function so its calling environment was examined  
so that vec[10] was returned.

-- 
david.

>
>>
>> Is there a way to check for missing function arguments, *and* which  
>> function
>> arguments are missing?
>>
>> For example
>> myfun = function(vec, i){
>>     curArgs = current.function.arguments()
>>     if(any(sapply(curArgs, missing))){
>>         stop()
>>     }
>>     ret = vec[i]
>>     ret
>> }
>
>> Obviously  "current.function.arguments()" is imaginary, but is there
>> something that would return the current arguments in a way that  
>> could be
>> passed to "missing()"??
>>
>>
>> I tried this:
>>     curfun = substr(match.call()[1],1,nchar(match.call()[1]))
>>     curargs = strsplit(deparse(args(curfun)),',')[[1]]
>>     curargs = gsub('function|\\(| |\\)','',curargs)
>>     sapply(curargs,missing(x))
>> and this:
>>     sapply(curargs,function(txt) eval(substitute(missing(x),  
>> list(x=txt))))
>>
>> inside the function, but missing doesn't like it when you do  
>> anything but
>> call it directly
>
> If you wrote the function, you should know what its args are, so you  
> could force them:
>
> > myfun
> function(vec, i){
>    force(vec)
>    force(i)
>    ret = vec[i]
>    ret
> }
> > myfun(vec)
> Error in force(i) : argument "i" is missing, with no default
>
> or test them explicitly with missing().  If you want to do this  
> automatically, then you shouldn't be using substrings and deparse,  
> you should work at the language level.  But I don't see the reason  
> you want to do this...
>
> Duncan Murdoch

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list