[R] Matrix diagonal help

David Winsemius dwinsemius at comcast.net
Fri Apr 23 20:56:38 CEST 2010


On Apr 23, 2010, at 2:30 PM, Dimitri Liakhovitski wrote:

> Your question is unclear.
>

Maybe not.

 > mtx <- matrix(1:16, 4)
 > nmtx <- matrix(0, 4,4)
 >  nmtx[1:4,1] <- mtx[row(mtx)==col(mtx)]
 >  nmtx[1:3,2] <- mtx[row(mtx)==col(mtx)-1]
 >  nmtx[1:2,3] <- mtx[row(mtx)==col(mtx)-2]
 >  nmtx[1:1,4] <- mtx[row(mtx)==col(mtx)-3]
 > nmtx
      [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    6   10   14    0
[3,]   11   15    0    0
[4,]   16    0    0    0

I think an sapply function that was set up to feed appropriately  
process elements in   1:nrow(mtx) could do the more general operation  
on an arbitrarily dimensioned argument. There are functions out there  
that will return sub and super diagonals and they might be more  
elegant that the col/row method offered here.

RSiteSearch("subdiagonal")

-- 
David.
> On Fri, Apr 23, 2010 at 5:45 AM, Usman Munir
> <usman.munir06 at googlemail.com> wrote:
>> Hi
>>
>> Suppose I have a matrix (cohort are rows and years are columns)
>>
>>
>>
>> [2000]  [2001]  [2002]  [2003]
>>
>> [C1]     0.01     0.03     0.02     0.09
>>
>> [C2]     0.06     0.05     0.07     0.11
>>
>> [C3]     0.1       0.5       0.4       0.98
>>
>> [C4]     0.7       0.6       0.2       0.77
>>
>>
>>
>>
>>
>> I want to extracts the diagonals to get a matrix which looks like  
>> this (C1
>> becomes C2 in 2002, C2 becomes C3 in 2003 and so on)
>>
>>
>>
>> [C1]     [C2]     [C3]     [C4]
>>
>> [2000]  0.01     0.06     0.1       0.7
>>
>> [2001]  0.05     0.5       0.6       0
>>
>> [2002]  0.4       0.2       0          0
>>
>> [2003]  0.77     0          0          0
>>
>>
>>
>> The matrix can be of any size (for simplicity I have created a  
>> 4*4). Is
>> there a function in R that does this? I know R has functions like R  
>> diag and
>> lower triangular but that doesn’t help. Any tips will be appreciated.
>>
>>
>> Thanks!
>>
>>        [[alternative HTML version deleted]]
>>
>>
>> ______________________________________________
>> 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.
>>
>>
>
>
>
> -- 
> Dimitri Liakhovitski
> Ninah.com
> Dimitri.Liakhovitski at ninah.com
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list