asachet
asachet

Reputation: 6921

Using R `outer` with `%in%` operator

I am trying to perform the following outer operation:

x <- c(1, 11)
choices <- list(1:10, 10:20)

outer(x, choices, FUN=`%in%`)

I expect the following matrix:

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

which would correspond to the following operations:

outer(x, choices, FUN=paste, sep=" %in% ")
     [,1]           [,2]           
[1,] "1 %in% 1:10"  "1 %in% 10:20" 
[2,] "11 %in% 1:10" "11 %in% 10:20"

But for some reason I am getting:

      [,1]  [,2]
[1,] FALSE FALSE
[2,] FALSE FALSE

What is happening?

Upvotes: 0

Views: 57

Answers (2)

Sotos
Sotos

Reputation: 51582

Another way that is close to your train of thought, would be to use expand.grid() to create the combinations, and then Map the two columns via %in% function, i.e.

d1 <- expand.grid(x, choices)
matrix(mapply(`%in%`, d1$Var1, d1$Var2), nrow = length(x))
#or you can use Map(`%in%`, ...) in order to keep results in a list

OR

As @nicola suggests, in order to make things better,

d1 <- expand.grid(list(x), choices) 
mapply(%in%, d1$Var1, d1$Var2)

both giving,

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

Upvotes: 2

nicola
nicola

Reputation: 24480

As expressed in the comments, the table argument of match (the function called by %in%) isn't intended to be a list (if it is, it gets coerced to a character). You should use vapply:

vapply(choices,function(y) x %in% y,logical(length(x)))
#      [,1]  [,2]
#[1,]  TRUE FALSE
#[2,] FALSE  TRUE

Upvotes: 3

Related Questions