Home > Enterprise >  Using which condition vs using simple condition
Using which condition vs using simple condition

Time:05-01

Which way is the best way to filter an object, using which or a simple condition?

x[-which(x > 0)] is the same of x[x <= 0]? Is there any case when the output is not the same?

CodePudding user response:

There are cases when the -which can give incorrect results

> x <- 1:5
> x[-which(x > 5)]
integer(0)
> x[x <=5]
[1] 1 2 3 4 5

A bug free approach is negation (!)

> x[!x > 5]
[1] 1 2 3 4 5
  • Related