[R] Diagonal matrix with off diagonal elements

Martin Maechler maechler at stat.math.ethz.ch
Mon Dec 24 14:00:22 CET 2007


>>>>> "PD" == Peter Dalgaard <p.dalgaard at biostat.ku.dk>
>>>>>     on Sat, 22 Dec 2007 11:29:30 +0100 writes:

    PD> Chris Stubben wrote:
    >> Also try the odiag function in the demogR package
    >> 
    >> odiag( 1:5, -1)
    >> [,1] [,2] [,3] [,4] [,5] [,6]
    >> [1,]    0    0    0    0    0    0
    >> [2,]    1    0    0    0    0    0
    >> [3,]    0    2    0    0    0    0
    >> [4,]    0    0    3    0    0    0
    >> [5,]    0    0    0    4    0    0
    >> [6,]    0    0    0    0    5    0
    >> 
    >> Chris
    >> 
    >> 
    PD> Also, this sort of pattern works

    >> m <- matrix(0,6,6)
    >> diag(m[-1,])<-1:5
    >> m
    PD> [,1] [,2] [,3] [,4] [,5] [,6]
    PD> [1,]    0    0    0    0    0    0
    PD> [2,]    1    0    0    0    0    0
    PD> [3,]    0    2    0    0    0    0
    PD> [4,]    0    0    3    0    0    0
    PD> [5,]    0    0    0    4    0    0
    PD> [6,]    0    0    0    0    5    0


Yes, indeed, *the* S- / R- answer.

and note that this also works with sparse matrices:

> library(Matrix)
> m <- Matrix(0,6,6)
> diag(m[-1,]) <- 1:5
> m
6 x 6 sparse Matrix of class "dgCMatrix"
                
[1,] . . . . . .
[2,] 1 . . . . .
[3,] . 2 . . . .
[4,] . . 3 . . .
[5,] . . . 4 . .
[6,] . . . . 5 .

- - - - - - - - - - - 

Merry Christmas' Eve  to all R-helpers!

Martin Maechler



More information about the R-help mailing list