[R] A combinatorial task. How to get rid of loops
    Serguei Kaniovski 
    Serguei.Kaniovski at wifo.ac.at
       
    Thu Aug  2 10:40:58 CEST 2007
    
    
  
Dear List,
I am looking for a faster way of accomplishing this:
# n is an integer larger than two
n <- 3
# matrix of 2^n binary outcomes
bmat <- as.matrix(expand.grid( rep( list(1:0), n))[, n:1])
# I would like to know which rows of "bmat" have "1" in the "i" and "j" 
coordinates, so for n=3 in coordinates 1-2, 1- 3, and 2-3
# I would like then to construct "choose( n, 2)" binary vectors of lengths 
2^n to indicate those rows with a "1"
# The loop below accomplishes this task. Is there a faster way of doing 
the same?
        library(combinat)
        # matrix of all pairwise combinations 
        cmat<-combn( n, 2)
 
        temp<-matrix(NA, nrow(bmat), ncol(cmat))
        for (i in 1:nrow(bmat))
        {
                for (j in 1:ncol(cmat))
                {
                        temp[ i, j]<-as.numeric( bmat[i,][cmat[1,j]] & 
bmat[i,][cmat[2,j]] == 1)
                }
        }
Thank you very much for your help!
Serguei Kaniovski
    
    
More information about the R-help
mailing list