【问题标题】:Alternative to for-loops替代 for 循环
【发布时间】:2014-08-25 05:57:13
【问题描述】:

考虑以下示例数据:

mapmatrix <- cbind(c(1,2,3,4,5,6),c(1,2,4,5,7,10))
arrayA <- c(1,2,4,7,10)
arrayB = rep(0,length(arrayA))
for(i in 1:length(arrayB))
{
arrayB[i] = which(mapmatrix[,2]==arrayA[i])
}

我被告知要尽可能避免 R 中的 for 循环。即使arrayA 有大约 400K 个元素,并且mapmatrix 的尺寸为 {200 万 x 2},我确实发现它非常耗时。如果我可以用更快的替代方案替换for-loop,将不胜感激。

【问题讨论】:

    标签: r for-loop vectorization


    【解决方案1】:

    你可以试试:

     match(arrayA, mapmatrix[,2])
     #[1] 1 2 3 5 6
    

    如果你有重复匹配,fmatch from library(fastmatch) 会更快

      library(fastmatch)
      fmatch(arrayA, mapmatrix[,2])
      #[1] 1 2 3 5 6
    

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 2020-12-22
      • 2020-11-24
      • 2012-09-20
      • 1970-01-01
      • 2017-06-06
      相关资源
      最近更新 更多