[R] yet another vectorization question

Adrian DUSA adi at roda.ro
Mon Jan 30 12:34:40 CET 2006


Dear R-helpers,

I'm trying to develop a function which specifies all possible expressions that 
can be formed using a certain number of variables. For example, with three 
variables A, B and C we can have
- presence/absence of A; B and C
- presence/absence of combinations of two of them
- presence/absence of all three

    A   B   C
1   0
2   1
3       0
4       1
5           0
6           1
7   0   0
8   0   1
9   1   0
10  1   1
11  0       0
12  0       1
13  1       0
14  1       1
15      0   0
16      0   1
17      1   0
18      1   1
19  0   0   0
20  0   0   1
21  0   1   0
22  0   1   1
23  1   0   0
24  1   0   1
25  1   1   0
26  1   1   1

My function (pasted below) while producing the desired result, still needs 
some more vectorizing; in particular, I can't figure out how could one modify 
the element of a matrix using apply on a different matrix...
To produce the above outcome, I use:
> all.expr(LETTERS[1:3])

"all.expr" <-
function(column.names) {
    ncolumns <- length(column.names)
    return.matrix <- matrix(NA, nrow=(3^ncolumns - 1), ncol=ncolumns)
    colnames(return.matrix) <- column.names
    rownames(return.matrix) <- 1:nrow(return.matrix)
    start.row <- 1
    all.combn <- sapply(1:ncolumns, function(idx) {
                                        as.matrix(combn(ncolumns, idx))
                                    }, simplify=FALSE)
    for (j in 1:length(all.combn)) {
        idk <- all.combn[[j]]
        tt <- matrix(NA, ncol=nrow(idk), nrow=2^nrow(idk))
        for (i in 1:nrow(idk)) {
            tt[,i] <- c(rep(0, 2^(nrow(idk) - i)), rep(1, 2^(nrow(idk) - i)))
        }

        ## This is _slow_ part, where I don't know how to vectorize:
        for (k in 1:ncol(idk)) {
            end.row <- start.row + nrow(tt) - 1
            return.matrix[start.row:end.row, idk[ , k]] <- tt
            start.row <- end.row + 1
        }
        ## How can one modify "return.matrix" using apply on "idk"?
    }
        return.matrix[is.na(return.matrix)] <- ""
        return.matrix
    }
}

Thank you in advance,
Adrian

-- 
Adrian DUSA
Romanian Social Data Archive
1, Schitu Magureanu Bd
050025 Bucharest sector 5
Romania
Tel./Fax: +40 21 3126618 \
          +40 21 3120210 / int.101




More information about the R-help mailing list