Search code examples
rmatrixr-factor

how to convert rows into factors in R?


For example, I have a matrix:

> a = cbind(sample(c(0,1),6,replace=T), sample(c(0,1),6,replace=T))
> a
     [,1] [,2]
[1,]    0    0
[2,]    0    0
[3,]    0    1
[4,]    1    0
[5,]    1    0
[6,]    1    1

I want to make a object b out of a so that b is a factor, with each level represent a different row in a. In this case, b would be:

> b
[1] 1 1 2 3 3 4
Levels: 1 2 3 4

I can do it in a dirty way, but I am wondering if there is an elegant solution?


Solution

  • A possible solution :

     b <- apply(a, 1, paste, collapse="_")
     b <- factor(b, levels=unique(b), labels=1:length(unique(b)))