Matrix to data.frame with factors

8 messages
Open this post in threaded view
|

Matrix to data.frame with factors

 Hi all, I have a matrix with 100 variables: each variable as a value of 0 or 1. What i want to do is convert this matrix to a data.frame but convert all the variables to factors (0 and 1) also. I know i can do this one variable a time but i have 100 variables... Any easy way of doing this?? Thanks a lot, Bruno
Open this post in threaded view
|

Re: Matrix to data.frame with factors

 This post has NOT been accepted by the mailing list yet. This post was updated on . Hi, Try this: set.seed(1) mat1<-matrix(sample(0:1,50,replace=TRUE),nrow=10,ncol=5)  dat1<-as.data.frame(mat1) dat2<- do.call(data.frame,lapply(dat1,as.factor))  str(dat2) #'data.frame': 10 obs. of  5 variables:  #\$ V1: Factor w/ 2 levels "0","1": 1 1 2 2 1 2 2 2 2 1  #\$ V2: Factor w/ 2 levels "0","1": 1 1 2 1 2 1 2 2 1 2  #\$ V3: Factor w/ 2 levels "0","1": 2 1 2 1 1 1 1 1 2 1  #\$ V4: Factor w/ 2 levels "0","1": 1 2 1 1 2 2 2 1 2 1  #\$ V5: Factor w/ 2 levels "0","1": 2 2 2 2 2 2 1 1 2 2 A.K.
Open this post in threaded view
|

Re: Matrix to data.frame with factors

 In reply to this post by brunosm Hello, Try the following. x <- matrix(sample(0:1, 12, TRUE), ncol = 4) y <- data.frame(apply(x, 2, factor)) str(y) Hope this helps, Rui Barradas Em 19-10-2012 12:04, brunosm escreveu: > Hi all, > > I have a matrix with 100 variables: each variable as a value of 0 or 1. > > What i want to do is convert this matrix to a data.frame but convert all the > variables to factors (0 and 1) also. > > I know i can do this one variable a time but i have 100 variables... > > Any easy way of doing this?? > > Thanks a lot, > > Bruno > > > > -- > View this message in context: http://r.789695.n4.nabble.com/Matrix-to-data-frame-with-factors-tp4646730.html> Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > [hidden email] mailing list > https://stat.ethz.ch/mailman/listinfo/r-help> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code. ______________________________________________ [hidden email] mailing list https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.
Open this post in threaded view
|

Re: Matrix to data.frame with factors

 In reply to this post by arun kirshna Thanks a lot!
Open this post in threaded view
|

Re: Matrix to data.frame with factors

Open this post in threaded view
|