Efficient ways of creating matrix based on vector matches

旧时模样 提交于 2021-01-07 01:05:48

问题


Please, consider the following code:

x <- c('dog', 'cow', 'horse', 'rabbit', 'bear', 'seal', 'lion', 'ostrich','cat', 'hamster')
y <- c('beaver', 'crow', 'donkey', 'lion', 'bear', 'fox', 'moose', 'mole')


mtx <- matrix(
  data = apply(
    X = expand.grid(
      'x' = x,
      'y' = y
    ),
    MARGIN = 1,
    FUN = function(df) {
      identical(df[['x']], df[['y']])
    }
  ),
  nrow = length(x)
)
Result
      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]
 [1,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [2,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [3,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [4,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [5,] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
 [6,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [7,] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
 [8,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [9,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[10,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

As you can see, I'm constructing a boolean matrix based on if there's a match between the elements in vector x and y. My real life vectors are of length 4000 and 30000, so I need something that is far more efficient. Thank you!

来源:https://stackoverflow.com/questions/64104342/efficient-ways-of-creating-matrix-based-on-vector-matches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!