ser2207860
ser2207860

Reputation: 65

Rank all columns in matrix and then reorder a different matrix using rank

I have a matrix x with 4 columns:

x <- structure(c(53L, 48L, 51L, 1012L, 59L, 55L, 27L, 27L, 21L,
  1905L, 20L, 24L, 21L, 20L, 21L, 258L, 22L, 25L, 23L, 27L, 16L,
  1900L, 24L, 21L), .Dim = c(6L, 4L))

I have an other matrix Y with same dimensions:

Y <- structure(c(-9, -7, -6.25, -6.25, -6, -5.75, -9, -7, -6.25,
  -6.25, -6, -5.75, -9, -7, -6.25, -6.25, -6, -5.75, -9, -7, -6.25,
  -6.25, -6, -5.75), .Dim = c(6L, 4L))

I want to rank the columns in matrix x and based on those rankings reorder the columns in matrix Y. I tried ranking columns in matrix x:

rank1 <- rank(x, ties.method= "first") # this does not give me column by column
rank1 <- rank(x[,1], ties.method= "first") # this gives individual column only

Is there a way for me to rank all columns in x and and reorder individual column in Y using that rank from x?

Upvotes: 3

Views: 1878

Answers (2)

Roland
Roland

Reputation: 132696

You can bind both matrices into an array and loop only ones with apply:

a <- array(c(x, y), dim=c(dim(x),2))
apply(a, 2, function(m) m[,2][rank(m[,1], ties.method= "first")])

#      [,1]  [,2]  [,3]  [,4]
#[1,] -6.25 -6.25 -7.00 -6.25
#[2,] -9.00 -6.00 -9.00 -6.00
#[3,] -7.00 -7.00 -6.25 -9.00
#[4,] -5.75 -5.75 -5.75 -5.75
#[5,] -6.00 -9.00 -6.25 -6.25
#[6,] -6.25 -6.25 -6.00 -7.00

Upvotes: 2

David Marx
David Marx

Reputation: 8558

Use apply to apply the function to each column:

X = matrix(rnorm(24), 6, 4)
Y = matrix(rnorm(24), 6, 4)

x.order = apply(X ,2, rank)

# alternatively, you can specify a ties method thusly:
x.order = apply(X,2, function(x){rank(x, ties.method="first")})

# now to reorder Y: 
sapply(1:ncol(Y), function(i){
  Y[x.order[,i],i]
}
       )

Upvotes: 3

Related Questions