Ya-Hsiu Chuang
2006-Oct-04 05:13 UTC
[R] how to generate matrices based on an indicator variable
Hi, I am trying to create matrices X's based on one indicator variable, r. Given a 4 x4 matrix X= [ 0,0,0,0 0,0,0,0 0,0,0,0 0,0,0,1] r= c(0, 0, 0, 1) I'd like to create separate matrices where when i = 1, X= [1,0,0,0 0,0,0,0 0,0,0,0 0,0,0,1] when i =2 , X= [0,0,0,0 0,1,0,0 0,0,0,0 0,0,0,1] when i = 3, X= [0,0,0,0 0,0,0,0 0,0,1,0 0,0,0,1] when i = 4, X= [0,0,0,0 0,0,0,0 0,0,0,0 0,0,0,1] Any suggestions would be very appreciated. Thanks [[alternative HTML version deleted]]
Gabor Grothendieck
2006-Oct-04 14:06 UTC
[R] how to generate matrices based on an indicator variable
This produces a list whose ith element is matrix Xi : X4 <- replace(matrix(0, 4, 4), cbind(4, 4), 1) lapply(1:4, function(i) replace(X4, cbind(i,i), 1)) On 10/4/06, Ya-Hsiu Chuang <amichuang at hotmail.com> wrote:> Hi, > > I am trying to create matrices X's based on one indicator variable, r. > > Given a 4 x4 matrix X= [ 0,0,0,0 > 0,0,0,0 > 0,0,0,0 > 0,0,0,1] > r= c(0, 0, 0, 1) > > I'd like to create separate matrices where > when i = 1, X= [1,0,0,0 > 0,0,0,0 > 0,0,0,0 > 0,0,0,1] > > when i =2 , X= [0,0,0,0 > 0,1,0,0 > 0,0,0,0 > 0,0,0,1] > > when i = 3, X= [0,0,0,0 > 0,0,0,0 > 0,0,1,0 > 0,0,0,1] > > when i = 4, X= [0,0,0,0 > 0,0,0,0 > 0,0,0,0 > 0,0,0,1] > > Any suggestions would be very appreciated. > > Thanks\