[R] for loop populate matrix

Dennis Murphy djmuser at gmail.com
Tue May 10 20:19:51 CEST 2011


Why loop?

matrix(rep(3:0, each = 5), ncol = 5, byrow = TRUE)
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    3    3    3
[2,]    2    2    2    2    2
[3,]    1    1    1    1    1
[4,]    0    0    0    0    0

HTH,
Dennis

On Tue, May 10, 2011 at 11:10 AM, Chris English <sglish at hotmail.com> wrote:
>
> Dear List,
> I am trying to populate a matrix using a for loop.This works.
>> four<- matrix(nrow=4,ncol=5)> for (j in 1:ncol(four)){+ for (i in 1:nrow(four)){+ four[i,j]<-i-1}+ }> print(four)     [,1] [,2] [,3] [,4] [,5][1,]    0    0    0    0    0[2,]    1    1    1    1    1[3,]    2    2    2    2    2[4,]    3    3    3    3    3
> What I would like is the inverse ofthe above, i.e.:     [,1] [,2] [,3] [,4] [,5][1,]     3    3    3    3    3[2,]     2    2    2    2    2[3,]     1    1    1    1    1[4,]     0    0    0    0    0
> and can't seem to get there.  Thanks,Chris
> ______________________________________________
> 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