[R] Removing elements from a vector matching a criteria, BUG in which() function

Rumen Kostadinov rkostadi at gmail.com
Sun Feb 13 18:46:52 CET 2011


Thanks Sarah,

Yes, the function behaves Exactly as documented:

check this out:
> a = c(1,2,3,4,5)
> a[which(a!=6)]
[1] 1 2 3 4 5
> a[!which(a==6)]
numeric(0)
 > a[-which(a==6)]
numeric(0)
> a[!a==6]
[1] 1 2 3 4 5

I guess this is just a "gotcha", since
I often use !which and -which to remove elements,
So one should use
a[which(a!=stuff to remove)]
instead of
a[-which(a==stuff to remove)]
a[!which(a==stuff to remove)]

Thanks,
R





On Sun, Feb 13, 2011 at 12:37 PM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
> If by "bug" you mean "function behaving exactly as documented."
>
> which() returns only the matches, the TRUE values. If there are no
> matches, it doesn't return anything.
>
> If I understand what you are trying to do, and I may not,
> a[which(a != 5)]
> is really what you want, and it is precisely to preserve
> that behavior that which() does what it does.
>
> Sarah
>
> ---
>
> which                   package:base                   R Documentation
>
> Description:
>
>     Give the ‘TRUE’ indices of a logical object, allowing for array
>     indices.
>
> Value:
>
>     If ‘arr.ind == FALSE’ (the default), an integer vector with
>     ‘length’ equal to ‘sum(x)’, i.e., to the number of ‘TRUE’s in ‘x’;
>     Basically, the result is ‘(1:length(x))[x]’.
>
> ---
> On Sun, Feb 13, 2011 at 11:59 AM, Rumen Kostadinov <rkostadi at gmail.com> wrote:
>> Dear all,
>>
>> I found a bug in the which() function.
>>
>> When trying to remove elements with the which function,
>> if the criteria is not matched, numeric(0) is returned instead of the
>> array itself.
>>
>> This is very weird.
>>
>>> a = c(1,2,3,4,5)
>>> a[!a==6]
>> [1] 1 2 3 4 5
>>> a[-which(a==6)]
>> numeric(0)
>>> a[-which(a==5)]
>> [1] 1 2 3 4
>>> a[!a==5]
>> [1] 1 2 3 4
>>
>> Is this correct? I believe this is a bug.
>>
>> I have to rewrite a lot of my R code to use
>> a = a[!criteria]
>> and not
>> a = a[-which(criteria)]
>>
>> R.
>>
>
>
> --
> Sarah Goslee
> http://www.functionaldiversity.org
>



More information about the R-help mailing list