[R] matrix problem

David Winsemius dwinsemius at comcast.net
Mon Jun 20 23:26:51 CEST 2011


On Jun 20, 2011, at 3:54 PM, Costis Ghionnis 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

Try:

 > m[y==1,1:4]<-rep( c(1,2,3,4), each= sum(y==1) )
 > m
      [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    3    4
[3,]    1    2    3    4
[4,]    0    0    0    0
[5,]    0    0    0    0

--  
David.
>
> 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...
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list