[R] rectify a program of seasonal dummies matrix

Friedrich Schuster mail at friedrich-schuster.de
Wed Aug 22 05:23:54 CEST 2007


Hello, 
 
the main problem seems to be the "if else", should be "else if". 

Your code is hard to read, maybe you should consider using more () {}: 

T <- 100;
br <- matrix(0,T,4);

for (i in 1:T) {
   for (j in 1:4) {
      if (i==j) {
         br[i,j] <- 1;
       }
       else if ((abs(i-j)%%4)==0) {
          br[i,j] <- 1;
        }
        else {
          br[i,j] <- 0;
        }
    }
 }

A simpler approach is creating a diagonal matrix and multply it : 

# create small diagonal matrix
mat = diag(x=1, nrow=4, ncol=4);
mat
# multiply diagonal matrix and re-dimension it   to 4 cols
br <- rep(mat, 25);
dim(br) <- c(100, 4);
br;

Hope this helps, 
FS

-- 

Friedrich Schuster
mail at friedrich-schuster.de



More information about the R-help mailing list