[R] matching matrix columns to a vector

Marc Schwartz marc_schwartz at comcast.net
Mon Nov 24 19:04:29 CET 2008


on 11/24/2008 10:03 AM Salas, Andria Kay wrote:
> I need help with (hopefully) just one more thing.  I have been
> fussing with this for quite some time and have decided just to give
> up and ask!  I want to match a column in a matrix to a vector.  I
> found a "which" command that I thought would be helpful as it does
> the following:
> 
>> g=c(1,5,3,2,7) which(g==5)
> [1] 2
> 
> As the above gave which placement in the g vector corresponded to 5
> (the second place), I need this command to give me which column in a
> matrix matches to a vector.
> 
> This is just a toy example of what I am trying to do:
>> t=matrix(1:12,3,4) v=c(1,2,3) which(t[,j]==v)
> 
> This does not work, and with my "real" matrices and vectors, I was
> getting outputs that did not make sense.  These examples are more to
> give an idea of what I am aiming to accomplish.
> 
> Thank you for all the help!! 

Presuming that you are comparing integers or characters:

mat <- matrix(1:12, 3, 4)
Vec <- 1:3

> mat
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

> Vec
[1] 1 2 3

> which(apply(mat, 2, identical, Vec))
[1] 1


Another possible option:

> which(apply(mat, 2, function(x) all(x == Vec)))
[1] 1


See ?apply, ?identical and ?all

Note that a variation on this would be required for floating point
numbers using all.equal().

You might also want to add error checking to be sure that:

  length(Vec) == nrow(mat)

lest you risk re-cycling of values.

HTH,

Marc Schwartz



More information about the R-help mailing list