matrix problem
How about: y <- c(1,1,1,3,2) m <- matrix(0, nrow=length(y), ncol=4) m[y==1, ] <- matrix(1:4, nrow=sum(y == 1), ncol=4, byrow=TRUE) or, depending on your actual problem y <- c(1,1,1,3,2) m <- matrix(0, nrow=length(y), ncol=4) m[y == 1,] <- col(m[y == 1,]) Sarah
On Mon, Jun 20, 2011 at 3:54 PM, Costis Ghionnis <conighion at gmail.com> wrote:
Hallo everyone! I have a problem about creating a matrix... Suppose we have a vector y<-c(1,1,1,3,2) and a zero matrix, m ,with nrows=length(y) and ncol=4. The matrix would look like this: 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 I want to change the first three rows with the vector c(1,2,3,4). I thought that with the command m[y==1,1:4]<-c(1,2,3,4) i would get 1 ? ? ? 2 ? ? ? 3 ? ? ? 4 1 ? ? ? 2 ? ? ? 3 ? ? ? 4 1 ? ? ? 2 ? ? ? 3 ? ? ? 4 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 but instead i am getting 1 ? ? ? 4 ? ? ? 3 ? ? ? 2 2 ? ? ? 1 ? ? ? 4 ? ? ? 3 3 ? ? ? 2 ? ? ? 1 ? ? ? 4 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 0 ? ? ? 0 ? ? ? 0 ? ? ? 0 It seems it is filling the data by col instead by row. I want to use this technique in more complicated problems. So i do not want to have to work with the transpose matrix. Do you know another way to make this work. Thank you...
Sarah Goslee http://www.functionaldiversity.org