Create a matrix by comparing differently sized vectors (without a for loop)

70 views Asked by At

I'm starting out in R, and pretty sure this is achievable via one of the apply functions.

I have two differently sized vectors, a <- c('A', 'B', 'C') and b <- c('A', 'B', 'C', 'D', 'E').

I want to compare the values of a and b, and where they match, put a one in a matrix, or zero if they do not match. So, using the above, something that looks like:

    A   B   C   D   E
A   1   0   0   0   0
B   0   1   0   0   0
C   0   0   1   0   0

I can do this via a for loop easy enough, but is there a more R-esque way of completing the above?

(Apologies, as I recognise this is probably a duplicate question, I'm just not sure what terms I should be searching for)

2

There are 2 answers

3
nicola On BEST ANSWER

Just try:

outer(a,b,"==")+0
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    0    0    0    0
#[2,]    0    1    0    0    0
#[3,]    0    0    1    0    0

If you want row and column names:

res<-outer(a,b,"==")+0
dimnames(res)<-list(a,b)

EDIT

Just a funnier one:

`[<-`(matrix(0,nrow=length(a),ncol=length(b)),
      cbind(seq_along(a),match(a,b)),
      1)
1
James On

You can use table, as long as you pad the smaller vector with NA's:

table(a=c(a,NA,NA),b)
   b
a   A B C D E
  A 1 0 0 0 0
  B 0 1 0 0 0
  C 0 0 1 0 0

You can do this more elegantly by doing changing the length of the smaller element to that of the larger one (new elements are set to NA by default):

length(a) <- length(b)
table(a,b)
   b
a   A B C D E
  A 1 0 0 0 0
  B 0 1 0 0 0
  C 0 0 1 0 0