[R] matrix of 1,0's to a data.frame of factors
Dimitris Rizopoulos
dimitris.rizopoulos at med.kuleuven.ac.be
Mon Dec 6 15:53:26 CET 2004
Hi Rajarshi,
try this:
mat <- sample(0:1, 20, TRUE); dim(mat) <- c(5,4)
mat[,1] <- 0; mat[,3] <- 1
#########
dat <- data.frame(mat)
dat[] <- lapply(dat, function(x) factor(x, levels=c("0","1")))
dat
lapply(dat, levels)
I hope it helps.
Best,
Dimitris
----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/336899
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat
http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm
----- Original Message -----
From: "Rajarshi Guha" <rxg218 at psu.edu>
To: "R" <r-help at stat.math.ethz.ch>
Sent: Monday, December 06, 2004 12:26 AM
Subject: [R] matrix of 1,0's to a data.frame of factors
> 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?
>
> Thanks,
> -------------------------------------------------------------------
> 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"
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list