我有数据
test <- 1:10
我想获得满足不同相关条件的test
指数。例如,
which(test>5)[1]
which(test>8)[1]
which(test>9)[1]
让
[1] 6
[1] 9
[1] 10
当单独执行时,有没有办法使用像这样的向量同时执行它们
bounds <- c(5,8,9)
然后产生一个包含bounds
中每个值的索引的向量?
有两种选择
findInterval(bounds, test) + 1
#[1] 6 9 10
哪个是最快的,或者
max.col(outer(bounds, test, `<`), 'first')
#[1] 6 9 10
这是最慢的,以及OP的帖子下面的评论:
sapply(bounds, function(x) which(test > x)[1])
#[1] 6 9 10
这既不是最快的,也不是最慢的。
只需使用申请:
sapply(bounds, function(x) which(test>x)[1])
[1] 6 9 10