【问题标题】:Faster Alternative to pairwise comparison using nested for loops in R使用 R 中的嵌套 for 循环更快地替代成对比较
【发布时间】:2018-07-12 17:54:51
【问题描述】:

我正在尝试找到一种更快的替代方法来比较数据框 X 中的每个观察结果 i 和观察结果 j。比如运行如下代码

for(i in 1:nrow(X)){
 for(j in 1:nrow(X)){
   if ( (sum(c(X$Feature1[i], X$Feature1[j])) == 0)&& ((X$Feature2[i] == X$Feature2[j])|(X$Feature3[i] == X$Feature3[j]) ) ){ 
  X$match[i]<-1
}}}

运行 20,000 个左右的观测值需要相当长的时间。 R中是否有任何人都知道的排序/比较算法?提前感谢您的宝贵时间!

【问题讨论】:

  • 请提供example data 以使您的问题可重现!
  • outer 可能有一个很好的解决方案...

标签: r sorting for-loop


【解决方案1】:

您可以在 sql 中或在 R 中使用sqldf 轻松完成此类操作。

X$match <- seq(nrow(X))
library(sqldf)
X$match <- sqldf("
  select    sum(b.Feature1 is not null) > 0 as match
  from      X a 
            left join X b
              on  a.Feature1 + b.Feature1 = 0
                  and (
                  a.Feature2 = b.Feature2
                  or a.Feature3 = b.Feature3)
  group by  a.match
  ")[[1]]

基础 R 版本可以是

X$match <- as.numeric(
            sapply(seq(nrow(X)), function(i){
                    any( (X$Feature1[i] + X$Feature1 == 0)
                         & (
                           (X$Feature2[i] == X$Feature2)
                           | (X$Feature3[i] == X$Feature3)))}))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2020-11-14
    相关资源
    最近更新 更多