[R] matrix of 1,0's to a data.frame of factors

Rajarshi Guha rxg218 at psu.edu
Mon Dec 6 00:26:45 CET 2004

Hi, I have an integer matrix consisting of 1's and 0's and I would like
to convert this to a data.frame where each column of the matrix becomes
a factor variable.  

Now, some columns of the matrix have only 1's or only 0's as a result
there is only 1 level for those columns in the data.frame. However it is
required that each factor have 2 levels. So my solution is:

    m <- function_returning_a_matrix()

    n <- data.frame(  apply(m,2,as.character) )
    for (i in 1:ncol(n)) {
        levels(n[,i]) <- c(1,0)

When m is 118 x 1024 the loop becomes very slow. So I then tried

    n <- data.frame(  apply(m,2,as.character) )
    apply(n,2,function(x) {levels(x) <- c(1,0)})

But this does not change the levels

Can anybody point me in the right direction?

Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
He who is in love with himself has at least this advantage -- he won't
encounter many rivals.
-- Georg Lichtenberg, "Aphorisms"

More information about the R-help mailing list