1

I want to compare every element of each member of the list with every element of each member of another list.

A = B = list(1, 2, c(1,2))

Expected outcome is follows:

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

I can solve similar task for the data.frame:

df = data.frame(A = c(1, 2, "1,2"), B = c(1, 2, "1,2"))
sapply(df$A, grepl, df$B)

which gives:

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

But that is not exactly the solution I'm looking for.

Any help is much appreciated!

Serhii
  • 362
  • 4
  • 15
  • I wouldn't say that the question is a duplicate. My question is specific while the other one is general. Moreover, the required output is completely different. – Serhii Sep 27 '18 at 13:08

1 Answers1

2

here is a complicated way:

A = B = list(1, 2, c(1,2))

outer(A, B, function(a,b) sapply((Vectorize(`%in%`))(a,b),any) )

#      [,1]  [,2] [,3]
#[1,]  TRUE FALSE TRUE
#[2,] FALSE  TRUE TRUE
#[3,]  TRUE  TRUE TRUE

Here is an easy way:

eg <- expand.grid(A,B)
matrix(
    mapply(function(x,y) {any(x %in% y)}, x = eg$Var1, y = eg$Var2 ), nrow = length(A), ncol = length(B)
)

(just for fun:)

matrix(
    mapply(function(x,y) {length(intersect(x, y)) != 0}, x = eg$Var1, y = eg$Var2 ), nrow = length(A), ncol = length(B)
)
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69