Reputation: 191
Having a matrix A like:
[,1] [,2] [,3] [,4]
[1,] 1 4 7 6
[2,] 2 5 8 1
[3,] 5 1 7 8
and a matrix B like:
[,1]
[1,] 8
[2,] 6
[3,] 1
[4,] 7
[5,] 5
[6,] 2
[7,] 3
[8,] 4
I want to get create a matrix C similar to A replacing A values with the rank of A values in matrix B. The result should be:
matrix C
[,1] [,2] [,3] [,4]
[1,] 3 8 4 2
[2,] 6 5 1 3
[3,] 5 3 4 1
Upvotes: 1
Views: 44
Reputation: 70266
You can use match
and adjust the dimensions:
C <- match(A, B)
dim(C) <- dim(A)
--
Example:
> set.seed(123)
> (A <- matrix(sample(1:8), ncol = 4))
[,1] [,2] [,3] [,4]
[1,] 3 8 4 2
[2,] 6 5 1 7
> (B <- matrix(sample(1:8), ncol= 1))
[,1]
[1,] 5
[2,] 4
[3,] 6
[4,] 3
[5,] 8
[6,] 2
[7,] 1
[8,] 7
> (C <- match(A, B))
[1] 4 3 5 1 2 7 6 8
> (dim(C) <- dim(A))
[1] 2 4
> C
[,1] [,2] [,3] [,4]
[1,] 4 5 2 6
[2,] 3 1 7 8
Upvotes: 2