[R] Testing for arguments in a function

Paul Johnson pauljohn32 at gmail.com
Thu Sep 29 01:26:28 CEST 2011


On Mon, Sep 26, 2011 at 2:39 PM, Gene Leynes <gleynes at gmail.com> 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)
>

Hello, Gene:

It seems to me the discussion of your question launches off into a
more abstract direction than we need here.  I've found it is wise to
name arguments to functions differently than variables in the
environment, so you don't have the function looking for i outside
itself.  And you can put each variable to a ridiculous default to
force an error when that option is not given.  "NAN" is nothing here,
just a string that has no meaning, so we get an error as you said you
wanted.


myfun <- function(ivec, ii=NAN){
ivec[ii]
}
myfun(1:40,10)

works

myfun(1:40)

Produces

Error in myfun(1:40) : object 'NAN' not found

If you are happy enough to just plop out an error, there's no need to worry.

Note the function can be written more succinctly than you originally
had it, and you are generally advised to use "<-" rather than "=" by
the R developers.




-- 
Paul E. Johnson
Professor, Political Science
1541 Lilac Lane, Room 504
University of Kansas



More information about the R-help mailing list