# [R] Testing for arguments in a function

Duncan Murdoch murdoch.duncan at gmail.com
Mon Sep 26 22:56:15 CEST 2011

```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.

>
> 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
>
> Using R 2.13.0 on a Windows 7 machine
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help