[R] Removing elements from a vector matching a criteria, BUG in which() function
Sarah Goslee
sarah.goslee at gmail.com
Sun Feb 13 18:37:40 CET 2011
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