[英]R: which() with vector in condition
I have data我有数据
test <- 1:10
and I would like to obtain the indices of test
that fulfill different related conditions.我想获得满足不同相关条件的
test
指标。 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
?然后产生一个向量,其中包含
bounds
每个值的索引?
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:这是最慢的,以及 OP 帖子下方的评论:
sapply(bounds, function(x) which(test > x)[1])
#[1] 6 9 10
which is neither the fastest, nor the slowest.这既不是最快的,也不是最慢的。
只需使用申请:
sapply(bounds, function(x) which(test>x)[1]) [1] 6 9 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.