3

我有一个x包含 4 列的矩阵:

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))

我有另一个Y具有相同尺寸的矩阵:

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))

我想对 matrix 中的列进行排名,x并根据这些排名对 matrix 中的列进行重新排序Y。我尝试在矩阵中对列进行排名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

有没有办法让我对所有列进行排名,x并在Y使用该排名时重新排序各个列x

4

2 回答 2

3

用于apply将函数应用于每一列:

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]
}
       )
于 2013-07-26T19:05:28.090 回答
2

您可以将两个矩阵绑定到一个数组中,并仅循环使用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
于 2013-07-26T19:20:53.547 回答