[R] How to make a matrix of a number of factors?

baptiste auguie baptiste.auguie at googlemail.com
Sun Nov 22 15:59:21 CET 2009


Hi,

Try this,

do.call(expand.grid, lapply(7:3, seq, from=1))


HTH,

baptiste


2009/11/22 Peng Yu <pengyu.ut at gmail.com>:
> I use the following code to generate a matrix of factors. I'm
> wondering if there is a way to make it more general so that I can have
> any number of factors (not necessarily 5).
>
> a=3
> b=4
> c=5
> d=6
> e=7
>
> A=1:a
> B=1:b
> C=1:c
> D=1:d
> E=1:e
>
> X=matrix(nr=a*b*c*d*e,nc=5)
>
> for(i_a in 1:a-1) {
>  for(i_b in 1:b-1) {
>    for(i_c in 1:c-1) {
>      for(i_d in 1:d-1) {
>        for(i_e in 1:e-1) {
>          X[(((i_a * b + i_b) * c + i_c) * d + i_d) * e + i_e + 1, ] =
> c(i_a+1, i_b+1, i_c+1, i_d+1, i_e+1)
>        }
>      }
>    }
>  }
> }
> print(X)
>
> ______________________________________________
> 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