将相同的数字分配给矩阵中的相似行

assigning the same number to similar rows in a matrix

我有一个 N 维方阵。我想定义一个大小为 N 的向量,它具有第一个分量: 与第一行相同的矩阵行的所有行索引。 作为第二个组成部分: 与第二行相同的矩阵行的所有行索引。

等等。

我正在研究 R,我已经尝试了一段时间了。任何关于如何进行的想法都将不胜感激。

myMatrix <- matrix(rep(1:4, 4), ncol = 2, byrow = FALSE)

     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    4    4
[5,]    1    1
[6,]    2    2
[7,]    3    3
[8,]    4    4

我尝试过的:

res <- list(NA)
for (i in 1:nrow(myMatrix)) {
  row_selected <- myMatrix[i,]
    res[[i]] <- which(myMatrix[i,]==row_selected)
}

res

dplyr版本:

# turn the matrix into a dataframe
myDf <- myMatrix %>% as.data.frame()

myDf %>% # and now get a left join of ...
    left_join(
        myDf %>% # ...the same dataframe with the index you were looking for
            distinct_all() %>%
            mutate(index = 1:nrow(.)))