【发布时间】:2015-07-07 02:15:14
【问题描述】:
我想获取某个向量子集的最小值的索引,但要获取原始向量中的索引,而不是重新编号的子集。
就目前而言,我一直在使用:
L = rnorm(20) # say this is the original vector
subset = runif(20)<0.3 # some conditions to extract the subset
ind_min = which.min(L[subset])
ind_sel = seq(L)[subset]
ind_min = ind_sel[ind_min]
但我想应该有更直接或更干净的东西。我一直在考虑使用一种技巧,例如:
L_tmp = L
L_tmp[!subset] = Inf
ind_min = which.min(L_tmp)
这显然更有效:
> microbenchmark(method_1(), method_2(), unit = "relative")
Unit: relative
expr min lq mean median uq max neval
method_1() 3.699562 3.249635 3.119666 3.076819 2.928259 3.225849 100
method_2() 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 100
但我对它并不满意,因为我想应该还有别的东西。有什么建议吗?
【问题讨论】: