如何在向量列表中查找向量的特定索引,其中索引在向量中给出? (没有 for 循环)
我想找到一种有效的操作来在列表中进行以下查找:
L = list(10:15,11:20)
a = c(3,7)
b = numeric()
for(i in 1:length(a)) b[i] = L[[i]][a[i]]
我认为 for
循环效率低下,我想这可以使用例如 sapply
更快地完成代码>.我的主要目标是当 L
很长时有效地完成此操作。
I would like to find an efficient operation to do the following look up in a list:
L = list(10:15,11:20)
a = c(3,7)
b = numeric()
for(i in 1:length(a)) b[i] = L[[i]][a[i]]
I think for
loops are inefficient and I imagine this can be done faster using, for example, sapply
. My main goal is to do this efficiently when L
is long.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一个
apply
方法是sapply()
。Another
apply
method would besapply()
.我们可以
在
base R
中使用vapply
来使用 Or,这会更快,或者使用
imap
作为紧凑选项We could use
Or in
base R
usingvapply
which would be fasteror use
imap
as a compact option更新:
您对循环的
的厌恶可能是没有根据的。我发现它可以非常依赖机器。在我当前的计算机上,使用
循环的基本rb
正确初始化,仅比
循环的某些rcpp
解决方案慢。请参阅下面更新的基准测试。loop1
解决方案已正确初始化。但是,我在其他机器上尝试了此操作,并且在某些上确实比
apply
解决方案要慢。使用
UNLIST
, cumsum 和长度
:基准标准的基础r r ro.
*我无法获得Akrun的
dplyr
解决方案来与较大的向量配合使用。UPDATE:
Your aversion to a
for
loop may be unfounded. I've found that it can be very machine dependent. On my current machine, withb
properly initialized, a base Rfor
loop is slower only than anRcpp
solution, and that just barely. See the updated benchmark below. Theloop1
solution is properly initialized. However, I've tried this on other machines, and on some thefor
loops are indeed slower than theapply
solutions.A base R vectorized solution using
unlist
,cumsum
, andlengths
:Benchmarking (tossing in an
Rcpp
solution)**I couldn't get akrun's
dplyr
solution to work with the larger vector.您可以使用
MAP
或mapply
。由于mapply
可以自动简化为向量,因此我们可以在这里使用它来获得b
一口气:You could use
Map
ormapply
. Sincemapply
can automatically simplify to a vector, we can could use that here to getb
in one go: