[R] create block diagonal with each rows
arun
smartpink111 at yahoo.com
Thu Jan 17 04:20:46 CET 2013
Hi,
May be this helps:
library(Matrix)
res1<-lapply(split(x,1:nrow(x)),function(y) sparseMatrix(i=rep(1:4,each=5),j=1:(4*5),x=y))
do.call(rbind,lapply(seq_along(res1),function(i) res1[[i]][i,]))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#[1,] 1 5 9 13 17 0 0 0 0 0 0 0 0 0
#[2,] 0 0 0 0 0 2 6 10 14 18 0 0 0 0
#[3,] 0 0 0 0 0 0 0 0 0 0 3 7 11 15
#[4,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0
# [,15] [,16] [,17] [,18] [,19] [,20]
#[1,] 0 0 0 0 0 0
#[2,] 0 0 0 0 0 0
#[3,] 19 0 0 0 0 0
#[4,] 0 4 8 12 16 20
A.K.
----- Original Message -----
From: Kathryn Lord <kathryn.lord2000 at gmail.com>
To: r-help <r-help at r-project.org>
Cc:
Sent: Wednesday, January 16, 2013 9:11 PM
Subject: [R] create block diagonal with each rows
Dear R users,
I'd like to create a block diagonal matrix with each rows in a matrix.
Here is a simple example. (In fact, the matrix is big)
x <- matrix(1:20, 4,5)
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
With each rows in matrix x, I'd like to make the matrix below.
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9][,10]
[,11][,12][,13][,14][,15][,16][,17][,18][,19][,20]
[1,] 1 5 9 13 17 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0
[2,] 0 0 0 0 0 2 6 10 14 18 0 0 0
0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0 3 7 11
15 19 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 4 8 12 16 20
Any suggestion will be greatly appreciated.
Best,
Kathryn Lord
[[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.
More information about the R-help
mailing list