![](/img/trans.png)
[英]R: Function to identify identical rows in a binary matrix and return a label vector
[英]Identify groups of identical rows in a matrix
tl;dr在 R 中识别矩阵中相同行组的惯用方法是什么?
给定一个 n×2 矩阵,其中一些行出现不止一次,
> mat <- matrix(c(2,5,5,3,4,6,2,5,4,6,4,6), ncol=2, byrow=T)
> mat
[,1] [,2]
[1,] 2 5
[2,] 5 3
[3,] 4 6
[4,] 2 5
[5,] 4 6
[6,] 4 6
我正在寻找相同行的行索引组。 在上面的示例中,行 (1,4) 是相同的,行 (3,5,6) 也是如此。 最后是第 (2) 行。 我希望得到这些组,以 R 中惯用的任何方式表示。
输出可能是这样的,
> groups <- matrix(c(1,1, 2,2, 3,3, 4,1, 5,3, 6,3), ncol=2, byrow=T)
> groups
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 1
[5,] 5 3
[6,] 6 3
其中第一列包含mat
的行索引,第二列包含每个行索引的组索引。 或者它可能是这样的:
> split(groups[,1], groups[,2])
$`1`
[1] 1 4
$`2`
[1] 2
$`3`
[1] 3 5 6
要么会做。 我不确定在 R 中代表组的最佳方式是什么,也欢迎就此提出建议。
出于基准测试目的,这里有一个更大的数据集:
set.seed(123)
n <- 10000000
mat <- matrix(sample.int(10, 2*n, replace = T), ncol=2)
cbind
与行序列以及行与行的unique
值之间的match
v1 <- paste(mat[,1], mat[,2])
# or if there are more columns
#v1 <- do.call(paste, as.data.frame(mat))
out <- cbind(seq_len(nrow(mat)), match(v1, unique(v1)))
-输出
> out
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 1
[5,] 5 3
[6,] 6 3
如果我们想要一个list
输出
split(out[,1], out[,2])
-输出
$`1`
[1] 1 4
$`2`
[1] 2
$`3`
[1] 3 5 6
借助 OP 的大数据
> system.time({
+ v1 <- paste(mat[,1], mat[,2])
+
+ out <- cbind(seq_len(nrow(mat)), match(v1, unique(v1)))
+
+ })
user system elapsed
2.603 0.130 2.706
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.