【问题标题】:Optimise row wise matrix comparison in R优化 R 中的逐行矩阵比较
【发布时间】:2020-12-13 14:04:06
【问题描述】:

我在 Google 上进行了广泛搜索,但似乎无法找到我的问题的答案。抱歉,如果以前有人问过这个问题。我有两个矩阵,a & b,每个都有相同的维度。我要做的是遍历 a 的行(从 i = 1 到 a 中的行数)并检查矩阵 a 的第 i 行中找到的 any 元素是否出现在相应行中矩阵 b。我有一个使用 sapply 的解决方案,但是对于非常大的矩阵,这会变得非常慢。我想知道是否有可能以某种方式对我的解决方案进行矢量化?以下示例:

# create example matrices
a = matrix(
  1:9,
  nrow = 3
)

b = matrix(
  4:12,
  nrow = 3
)

# iterate over rows in a....
# returns TRUE for each row of a where any element in ith row is found in the corresponding row i of matrix b
sapply(1:nrow(a), function(x){ any(a[x,] %in% b[x,])})

# however, for large matrices this performs quite poorly. is it possible to vectorise?

a = matrix(
  runif(14000000),
  nrow = 7000000
)

b = matrix(
  runif(14000000),
  nrow = 7000000
)

system.time({
 sapply(1:nrow(a), function(x){ any(a[x,] %in% b[x,])})
})


【问题讨论】:

    标签: r matrix


    【解决方案1】:

    使用 apply 查找任何 0 差异:

    a <- sample(1:3, 9, replace = TRUE)
    b <- sample(1:3, 9, replace = TRUE)
    a <- matrix(a, ncol = 3)
    b <- matrix(b, ncol = 3)
    
    diff <- (a - b)
    apply(diff, 1, function(x) which(x == 0)) # actual indexes = 0
    apply(diff, 1, function(x) any(x == 0)) # row check only
    

    【讨论】:

      【解决方案2】:

      也许你可以试试intersect + asplit 如下所示

      lengths(Map(intersect, asplit(a, 1), asplit(b, 1))) > 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-24
        • 2020-07-15
        • 2017-08-13
        • 1970-01-01
        • 2013-05-04
        • 2020-11-22
        • 1970-01-01
        相关资源
        最近更新 更多