[英]R: which() with vector in condition
我有數據
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.