[R] Identify row indices corresponding to each distinct row of a matrix

li li h@nn@h@hlx @ending from gm@il@com
Thu Nov 8 04:55:42 CET 2018


Hi all,
   I use the following example to illustrate my question. As you can see,
in matrix C some rows are repeated and I would like to find the indices of
the rows corresponding to each of the distinct rows.
  For example, for the row c(1,9), I have used the "which" function to
identify the row indices corresponding to c(1,9). Using this approach, in
order to cover all distinct rows, I need to use a for loop.
   I am wondering whether there is an easier way where a for loop can be
avoided?
   Thanks very much!
      Hanna



> A <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16),8,2)> B <- rbind(A,A,A)> C <- as.data.frame(B[sample(nrow(B)),])> C   V1 V2
1   1  9
2   2 10
3   3 11
4   5 13
5   7 15
6   6 14
7   4 12
8   3 11
9   8 16
10  5 13
11  7 15
12  2 10
13  1  9
14  8 16
15  1  9
16  3 11
17  7 15
18  4 12
19  2 10
20  6 14
21  4 12
22  8 16
23  5 13
24  6 14> T <- unique(C)> T  V1 V2
1  1  9
2  2 10
3  3 11
4  5 13
5  7 15
6  6 14
7  4 12
9  8 16> > i <- 1                    > which(C[,1]==T[i,1]&
C[,2]==T[i,2])[1]  1 13 15

	[[alternative HTML version deleted]]



More information about the R-help mailing list