[R] rectify a program of seasonal dummies matrix

Uwe Ligges ligges at statistik.uni-dortmund.de
Wed Aug 22 10:00:10 CEST 2007



Friedrich Schuster wrote:
> 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);

Thanks for the contribution. Please note:
a) It is a bad idea to have a variable called T. Some people still use 
it as a logical value even if they should not.
b) R does not need any ";" at the end of a line.

Uwe Ligges


> 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
>



More information about the R-help mailing list