Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function for doing all pairwise comparisons for two vectors

Tags:

r

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?

like image 602
evt Avatar asked Mar 25 '13 21:03

evt


1 Answers

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.

like image 171
Glen_b Avatar answered Sep 22 '22 19:09

Glen_b