简体   繁体   中英

R: Function to identify identical rows in a binary matrix and return a label vector

I am looking for a (fast) function that identifies identical rows in a matrix containing only integers 0 and 1, that returns a vector of labels telling me which rows are identical.

Here is a reproducible example of what I want to achieve:

mat = rbinom(n=1000, size=1, prob=0.8)
dim(mat) = c(200, 5)

umat = unique(mat)
idVec = numeric(nrow(mat))
for(i in seq_len(nrow(umat))){
  for(j in seq_len(nrow(mat))){
    if(isTRUE(all.equal(mat[j,], umat[i,]))){
      idVec[j] = i
    }    
  }
}
cbind(idVec, mat)
table(idVec)

Actually this function http://www.stat.washington.edu/~rje42/lca/html/group.html would just be perfect. However, it's not on CRAN, no source code, and was built prior to R 3.0.0.

Thank's for your help!

I reduced your example mat a bit for better handling:

mat = rbinom(n=100, size=1, prob=0.8)
dim(mat) = c(20, 5)

Now you can create the idVec like this (assuming you don't care about the actual numbers, just the correct "mapping"):

idVec <- as.integer(factor(apply(mat, 1, toString)))

And of course you can add it or create the table:

> cbind(idVec, mat)
      idVec          
 [1,]     6 1 1 1 1 1
 [2,]     5 1 1 1 1 0
 [3,]     6 1 1 1 1 1
 [4,]     5 1 1 1 1 0
 [5,]     1 0 1 1 0 1
 [6,]     2 0 1 1 1 1
 [7,]     6 1 1 1 1 1
 [8,]     6 1 1 1 1 1
 [9,]     6 1 1 1 1 1
[10,]     5 1 1 1 1 0
[11,]     4 1 0 1 1 1
[12,]     5 1 1 1 1 0
[13,]     6 1 1 1 1 1
[14,]     4 1 0 1 1 1
[15,]     3 1 0 1 0 0
[16,]     1 0 1 1 0 1
[17,]     6 1 1 1 1 1
[18,]     6 1 1 1 1 1
[19,]     6 1 1 1 1 1
[20,]     2 0 1 1 1 1
> table(idVec)
idVec
1 2 3 4 5 6 
2 2 1 2 4 9 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM