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

Peng Yu pengyu.ut at gmail.com
Sun Nov 22 15:42:32 CET 2009


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)




More information about the R-help mailing list