Matrix comparing each element in vector1 with each element in vector2

I want to compare each element in one vector (D) with each element in another vector (E) to get a matrix with dimensions length (D) xlength (E).

The corresponding comparison is:

abs(D[i]-E[j])<0.1

So for

D <- c(1:5)
E <- c(2:6)

I want to receive

       [,1]  [,2]  [,3]  [,4]  [,5]
[1,] FALSE  TRUE FALSE FALSE FALSE
[2,] FALSE FALSE  TRUE FALSE FALSE
[3,] FALSE FALSE FALSE  TRUE FALSE
[4,] FALSE FALSE FALSE FALSE  TRUE
[5,] FALSE FALSE FALSE FALSE FALSE

(Or 1s and 0s for the same effect)

I was able to get this conclusion by doing something awkwardly like:

rbind(D%in%E[1],D%in%E[2],D%in%E[3],D%in%E[4],D%in%E[5])

and I could write a loop for 1: length (E), but certainly there is a simple name and simple code for this operation? I struggled to find a language to find the answer to this question.

+4
source share
2 answers

outer D E:

outer(E, D, function(x, y) abs(x-y) <= 0.1)
#       [,1]  [,2]  [,3]  [,4]  [,5]
# [1,] FALSE  TRUE FALSE FALSE FALSE
# [2,] FALSE FALSE  TRUE FALSE FALSE
# [3,] FALSE FALSE FALSE  TRUE FALSE
# [4,] FALSE FALSE FALSE FALSE  TRUE
# [5,] FALSE FALSE FALSE FALSE FALSE

, :

  • : x y, E[1] D, E[2], ..
+5

( @alexis_laz):

n = length(E)
abs(E - matrix(D, ncol=n, nrow=n, byrow=T))<0.1

#      [,1]  [,2]  [,3]  [,4]  [,5]
#[1,] FALSE  TRUE FALSE FALSE FALSE
#[2,] FALSE FALSE  TRUE FALSE FALSE
#[3,] FALSE FALSE FALSE  TRUE FALSE
#[4,] FALSE FALSE FALSE FALSE  TRUE
#[5,] FALSE FALSE FALSE FALSE FALSE
+1

Source: https://habr.com/ru/post/1611226/


All Articles