R: which() with vector in condition

bumblebee Source

I have data

test <- 1:10

and I would like to obtain the indices of test that fulfill different related conditions. For example,

which(test>5)[1] 
which(test>8)[1]
which(test>9)[1]

yield

[1]  6  
[1]  9 
[1]  10

when carried out individually, but is there a way to execute them simultaneously using a vector like

bounds <- c(5,8,9)

that then yields a vector containing the indices for each value in bounds?

rwhich

Answers

answered 5 days ago divibisan #1

Just use apply:

sapply(bounds, function(x) which(test>x)[1]) [1] 6 9 10

answered 5 days ago akrun #2

A couple of options are

findInterval(bounds, test) + 1
#[1]  6  9 10

which is the fastest, or

max.col(outer(bounds, test, `<`), 'first')
#[1]  6  9 10

which is the slowest, along with the commented one below the OP's post:

sapply(bounds, function(x) which(test > x)[1])
#[1] 6 9 10

which is neither the fastest, nor the slowest.

comments powered by Disqus