[R] Testing for arguments in a function

Duncan Murdoch murdoch.duncan at gmail.com
Tue Sep 27 02:04:20 CEST 2011


On 11-09-26 5:15 PM, David Winsemius wrote:
>
> 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.
>

In which R version?  In 2.13.1 patched (from a few weeks ago) I get this:

 > ## Expected input and behavior:
 > myfun(vec, i)
[1] 10
 >
 > ## Missing an argument, but error is not caught!
 > ## How is subsetting even possible here???
 > myfun(vec)
   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
  [16]  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30
  [31]  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45
  [46]  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60
  [61]  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75
  [76]  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
  [91]  91  92  93  94  95  96  97  98  99 100
 >

The second set of output is the same as vec[].

Duncan Murdoch



More information about the R-help mailing list