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

有帮助吗?

解决方案

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:

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’ returns a permutation which rearranges its first argument into ascending or descending order, breaking ties by further arguments. ... 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归因
不隶属于 StackOverflow
scroll top