[R] How to index a matrix with different row-number for each column?

Zhenjiang Lan lan.zhenjiang at gmail.com
Tue Jun 12 18:19:08 CEST 2012


I thought I solved my question but actually not...
What I really want is to translate a matrix:

mt1:
     [,1] [,2] [,3]
[1,] "G"  "A"  "A"
[2,] "C"  "T"  "C"

mt2:
     [,1] [,2] [,3]
[1,]    1    2    2
[2,]    2    1    2
[3,]    2    2    2
[4,]    1    1    1

I want to translate all the "1" and "2" into "A T G C"
that is, change column1 into G(1) and C(2), column2 into A(1) and T(2)...

The output should be :
     [,1] [,2] [,3]
[1,]    G    T    C
[2,]    C    A    C
[3,]    C    T    C
[4,]    G    A    A

I don't know why I'm alway trying to find a solution without using
loop... But I do want..


On Tue, Jun 12, 2012 at 10:36 AM, Zhenjiang Lan <lan.zhenjiang at gmail.com> wrote:
> Thank you very much! that's exactly what I want.
>
> On Tue, Jun 12, 2012 at 10:32 AM, R. Michael Weylandt
> <michael.weylandt at gmail.com> wrote:
>> I think you are looking for
>>
>> mt[cbind(vt, seq_along(vt))]
>>
>> which uses some trickines known as matrix indexing (basically, the two
>> columns created by cbind() are considered row & col indices -- then
>> seq_along() gives the col1,col2, bit as needed.
>>
>> HTH,
>>
>> Michael
>>
>> On Tue, Jun 12, 2012 at 10:28 AM, Zhenjiang Lan <lan.zhenjiang at gmail.com> wrote:
>>> here's my question: suppose I have a matrix:
>>>
>>>    mt<-matrix(1:12,ncol=6)
>>>
>>> now I have a vector
>>>
>>>    vt<-c(1,2,2,2,1,2)
>>>
>>> which means I want to get:
>>> the 1st row for column1;
>>> the 2nd row for column2;
>>> the 2nd row for column3;
>>> the 2nd row for column4;
>>> ...
>>>
>>> that what I want is this vector:
>>> 1,4,6,8,9,12
>>>
>>> Does anyone know how to do this fast?
>>> I know I can use for-loop to travel all columns,but that's not what I want.
>>>
>>> ______________________________________________
>>> 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