简体   繁体   English

R:创建行名和列名组合的列表,并对它们进行排名

[英]R: Create a list of combinations of row names and column names and rank them

I have two matrices: 我有两个矩阵:

matrix1:

     col1   col2
row1  5      4

row2  4      6




matrix2:

     col1   col2
row1  48     50

row2  47     46

What I want is a new matrix or table: 我想要的是一个新的矩阵或表:

          Dim1   Dim2   rank
row2col1   4      47     1
row1col2   4      50     2
row1col1   5      48     3
row2col2   6      46     4

As you can see, I want to rank different combinations of rows and columns first based on dim1, and if there is a tie, by using dim2. 如您所见,我想首先基于dim1对行和列的不同组合进行排名,如果有平局,可以使用dim2进行排名。 The result matrix must be sorted using this rank. 必须使用此等级对结果矩阵进行排序。 How can I achieve it? 我该如何实现? It is worth noting that matrix1 and 2 contains values for the dim1 and dim2 and have exactly the same column and row names. 值得注意的是,matrix1和2包含dim1和dim2的值,并且具有完全相同的列名和行名。

Assuming there are no duplicate rows: 假设没有重复的行:

a <- array(c(5,4,4,6,48,47,50,46),c(2,2,2))
dimnames(a) <- list(c("row1", "row2"), c("col1", "col2"), c("m1", "m2"))
# , , m1
# 
# col1 col2
# row1    5    4
# row2    4    6
# 
# , , m2
# 
# col1 col2
# row1   48   50
# row2   47   46

library(reshape2)
b <- acast(melt(a), Var1+Var2~Var3)
b <- b[order(b[,1], b[,2]),]

Or for an arbitrary number of columns: 或对于任意数量的列:

b <- b[do.call(order, lapply(seq_len(ncol(b)), function(i) b[,i])),]
#add ranks
b <- cbind(b, rank=seq_len(nrow(b)))

#           m1 m2 rank
# row2_col1  4 47    1
# row1_col2  4 50    2
# row1_col1  5 48    3
# row2_col2  6 46    4

Have a look at ?order : 看一下?order

df <- data.frame(Dim1=c(6,5,4,4), Dim2=c(46,48,47,50))

o <- order(df$Dim1, df$Dim2)

df[o, ]
#  Dim1 Dim2
#3    4   47
#4    4   50
#2    5   48
#1    6   46

From ?order : ?order

'order' returns a permutation which rearranges its first argument into ascending or descending order, breaking ties by further arguments. “ order”返回一个排列,该排列将其第一个参数重新排列为升序或降序,并通过其他参数打破联系。 ... In the case of ties in the first vector, values in the second are used to break the ties. ...如果是第一个向量中的平局,则使用第二个向量中的值来打破平局。 If the values are still tied, values in the later arguments are used to break the tie 如果这些值仍然是平局,则后面的参数中的值将用于打破平局

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM