[R] matching matrix columns to a vector

David Winsemius dwinsemius at comcast.net
Tue Nov 25 20:35:35 CET 2008


It would be safer to substitute "all.equal(x,v) == TRUE" for every  
instance where "identical(x,v)" appears below.

Identical does not behave as I believed it did, and all.equal needs to  
be tested in order to to properly handle situations in which it  
returns a character value.

 > apply(t,2,function(x) all.equal(x,v))
[1] "TRUE"                                "Mean relative difference:  
0.6"
[3] "Mean relative difference: 0.75"      "Mean relative difference:  
0.8181818"
 > which(apply(t,2,function(x)all.equal(x,v)))
Error in which(apply(t, 2, function(x) all.equal(x, v))) :
   argument to 'which' is not logical


 > apply(t,2,function(x) all.equal(x,v) == TRUE)
[1]  TRUE FALSE FALSE FALSE
 > which(apply(t,2,function(x) all.equal(x,v) == TRUE))
[1] 1

-- 
David Winsemius

On Nov 24, 2008, at 1:02 PM, David Winsemius wrote:

> Consider:
>
> > apply(t,2,function(x)identical(x,v))
> [1]  TRUE FALSE FALSE FALSE
>
> > apply(t,2,function(x)identical(x,v))+0
> [1] 1 0 0 0
>
> and if you wanted to get the position you could use which:
> > which(apply(t,2,function(x)identical(x,v)))
> [1] 1
>
> > t[,4] <- v
> > which(apply(t,2,function(x)identical(x,v)))
> [1] 1 4
>
> -- David Winsemius
> On Nov 24, 2008, at 11: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!!
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list