evt
evt

Reputation: 971

R function for doing all pairwise comparisons for two vectors

I am guessing that this exists somewhere in R already, so maybe you could point me to it.

I have two numerical vectors, A and B.

A <- c(1,2,3)
B <- c(2,3,4)

I am looking for a function which does something like doing each possible comparison between A and B, and returning a vector of the T/F of those comparisons.

So in this case, it would compare: 1>2 then 1>3 then 1>4 then 2,2 then 2>3 then 2>4 then 3>2 then 3>4 and return:

FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE

It would be fine if it returned the differences, as that could be easily converted.

Does a function like this already exist?

Upvotes: 7

Views: 7634

Answers (1)

Glen_b
Glen_b

Reputation: 8252

outer is probably the function you want. However, it returns a matrix, so we need to get a vector. Here's one way of many:

 a <- 1:3
 b <- 2:4
 as.vector(outer(a,b,">"))
[1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE

(that's not the order you specified though; it is, however, a consistent order)

Also:

 as.vector(t(outer(a,b,">")))
[1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE

Now for differences:

> as.vector(outer(a,b,"-"))
[1] -1  0  1 -2 -1  0 -3 -2 -1

I find that outer is very useful. I use it regularly.

Upvotes: 11

Related Questions