优化R中的行矩阵比较

优化R中的行矩阵比较,r,matrix,R,Matrix,我在谷歌上搜索了很长时间,似乎找不到问题的答案。如果以前有人问过,我会道歉。我有两个矩阵,a和b,每个都有相同的维数。我要做的是迭代a的行(从I=1到a中的行数),并检查矩阵a的行I中找到的任何元素是否出现在矩阵b的对应行中。我有一个使用sapply的解决方案,但是对于非常大的矩阵,这会变得非常缓慢。我想知道是否有可能以某种方式将我的解决方案矢量化?举例如下: # create example matrices a = matrix( 1:9, nrow = 3 ) b = matri

我在谷歌上搜索了很长时间,似乎找不到问题的答案。如果以前有人问过,我会道歉。我有两个矩阵,a和b,每个都有相同的维数。我要做的是迭代a的行(从I=1到a中的行数),并检查矩阵a的行I中找到的任何元素是否出现在矩阵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,])})
})



使用“应用”查找任何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

a也许你可以尝试
intersect
+
asplit
如下

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