Create multiple matrices from 2 bigger ones in R

I have 2 matrices, A (1000x21) and B (1000x7). Matrix A has individuals(=1000) in the rows and their consumption in 21 days at the columns. Matrix B has the SAME individuals(=1000) in the rows and some weights for each day of the week(=7) in the columns.

What I would like to have in the end is 1000 (with the dimension of 2x21) matrices (one for each individual), lets call them $X_{i}$. In the first row of each $X_{i}$ I would like to have the consumption of the individual $i$ each of the 21 days (this will come from matrix A), and at the second row of the $X_{i}$ I would like to have the respective weight of that day (this will come from matrix B).

So matrix A looks like $[cons_{1,1} \ cons_{1,2} \ ... \ cons_{1,21} \\ \ cons_{2,1} \ cons_{2,2} \ ... \ cons_{2,21} \\ . \\ . \\ . \\ \ cons_{1000,1} \ cons_{1000,2} \ ... \ cons_{1000,21}]$

Matrix B looks like $[weight_{1,1} \ weight_{1,2} \ ... \ weight_{1,7} \\ \ weight_{2,1} \ weight_{2,2} \ ... \ weight_{2,7} \\ . \\ . \\ . \\ \ weight_{1000,1} \ weight_{1000,2} \ ... \ weight_{1000,7}]$

And I would like the matrix $X_{i}$ to be like $[cons_{i,1} \ cons_{i,2} \ ... \ cons_{i,21} \\ \ weight_{i,1} \ weight_{i,2} \ ... weight_{i,k}]$

Any ideas how to do this in R in a loop ?

• Do you want to have 1000 separate matrix objects or have them in a list? Aug 18 '16 at 9:41

This will extract the rows from matrix A and B.

matrix(c(A[x,],rep(B[x,],times=3)),nrow=2,byrow=T)

If you want to get them into a list (recommend)

single<-lapply(c(1:1000), function(x) matrix(c(A[x,],rep(B[x,],times=3)),nrow=2,byrow=T))

To put them all in diagonal matrix with adiag from magic package