Jorge Mendoza Ruiz
Jorge Mendoza Ruiz

Reputation: 316

Counting number of rows equal to the rows in another matrix in R

I have the next problem. I have a matrix A whose rows are all possible permutations of the sequence seq(1:D). I have other D matrixes whose rows are also permutations. I want to generate a matrix with dimension D!xD whose [i,j] component is the number of rows identical to the j-th row of A in the i-th matrix. A litle example:

A= [1,2,3
    1,3,2
    2,1,3
    2,3,1
    3,1,2
    3,2,1]   #Matrix of all posible permutations

and

B= [1,2,3
    1,2,3
    3,2,1] #One of my D matrixes

and

C=[2,1,3
   1,2,3
   2,3,1]. #Another of my matrixes

The output I´m looking for is

count= [2,1
        0,0
        0,1
        0,1
        0,0
        1,0]. 

Could you help me? I don't want to use a loop because I have enough in my code and this is supposed to be into a loop.

Thank you so much-

Upvotes: 0

Views: 194

Answers (2)

Sathish
Sathish

Reputation: 12723

Data:

A <- matrix( c(1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1), nrow = 6, ncol = 3, byrow = TRUE)
B <- matrix( c( 1,2,3,1,2,3,3,2,1), nrow = 3, byrow = TRUE)
C <- matrix( c(2,1,3,1,2,3,2,3,1), nrow = 3, byrow = TRUE)

Code: combine the columns into one number string per row, and compare the vector of A with B and C.

A <- apply(A, 1, paste0, collapse = "_")
B <- apply(B, 1, paste0, collapse = "_")
C <- apply(C, 1, paste0, collapse = "_")

sapply( list(B,C), function(x) {
  sapply( A, function(y) sum(x %in% y))
})

Output:

#      [,1] [,2]
# [1,]    2    1
# [2,]    0    0
# [3,]    0    1
# [4,]    0    1
# [5,]    0    0
# [6,]    1    0

Upvotes: 1

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84559

Another solution, a bit similar to @Sathish's one:

A <- matrix( c(1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1), nrow = 6, ncol = 3, byrow = TRUE)
B <- matrix( c( 1,2,3,1,2,3,3,2,1), nrow = 3, byrow = TRUE)
C <- matrix( c(2,1,3,1,2,3,2,3,1), nrow = 3, byrow = TRUE)

# count rows of a matrix M equal to a vector vect
rowsEqualToVector <- function(vect, M){
  sum(apply(M, 1, function(matRow) identical(vect, matRow)))
}

# apply the previous function to each row of a matrix A
sameRows <- function(A,M){
  apply(A, 1, function(row) rowsEqualToVector(row, M))
}

# map the previous function to a list of matrices
sapply(list(B,C), function(M) sameRows(A,M))

Output:

> sapply(list(B,C), function(M) sameRows(A,M))
     [,1] [,2]
[1,]    2    1
[2,]    0    0
[3,]    0    1
[4,]    0    1
[5,]    0    0
[6,]    1    0

Upvotes: 0

Related Questions