按条件对R矩阵的行和列进行排序 [英] Ordering rows and columns of R Matrix by criteria

查看:1190
本文介绍了按条件对R矩阵的行和列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个矩阵,像这样:

I have a matrix in R like this:

  A B C D E F
A 2 5 0 1 3 6
B 5 0 0 1 5 9
C 0 0 0 0 0 1
D 6 1 1 3 4 4
E 3 1 5 2 1 6
F 0 0 1 1 7 9

mat = structure(c(2L, 5L, 0L, 6L, 3L, 0L, 5L, 0L, 0L, 1L, 1L, 0L, 0L, 
0L, 0L, 1L, 5L, 1L, 1L, 1L, 0L, 3L, 2L, 1L, 3L, 5L, 0L, 4L, 1L, 
7L, 6L, 9L, 1L, 4L, 6L, 9L), .Dim = c(6L, 6L), .Dimnames = list(
    c("A", "B", "C", "D", "E", "F"), c("A", "B", "C", "D", "E", 
    "F")))

矩阵不对称.

我想根据以下条件对行和列进行重新排序:

I want to reorder the rows and columns according to the following criteria:

NAME TYPE
A    Dog
B    Cat
C    Cat
D    Other
E    Cat
F    Dog

crit = structure(list(NAME = c("A", "B", "C", "D", "E", "F"), TYPE = c("Dog", 
"Cat", "Cat", "Other", "Cat", "Dog")), .Names = c("NAME", "TYPE"
), row.names = c(NA, -6L), class = "data.frame")

我正在尝试对矩阵行和列进行重新排序,以便将每个类别组合在一起:

I am trying to get the matrix rows and columns to be re-ordered, so that each category is grouped together:

 A F B C E D
A
F
B
C
E
D

我无法找到任何合理的方法来做到这一点.

I am un-able to find any reasonable way of doing this.

万一重要,或者使事情变得简单,我可以摆脱其他"类别,而只坚持使用猫"和狗".

In case it matters, or makes things simpler, I can get rid of the category 'Others' and just stick with 'Cat' and 'Dog'.

我需要找到一种方法来编写代码,以使这种重新排序发生,因为矩阵很大.

I need to find a way to write code for this re-ordering to happen as the matrix is quite big.

推荐答案

在基础中,只需按order进行索引:

In base, just index by order:

mat[order(crit$TYPE), order(crit$TYPE)]
#
#   B C E A F D
# B 0 0 5 5 9 1
# C 0 0 0 0 1 0
# E 1 5 1 3 6 2
# A 5 0 3 2 6 1
# F 0 1 7 0 9 1
# D 1 1 4 6 4 3

它按字母顺序排序crit$TYPE,因此Cat(BCE)在Dog(AF)之前.如果要设置顺序,请使用因子水平:

It orders on an alphabetical sort of crit$TYPE, so Cat (B, C, and E) comes before Dog (A and F). If you want to set the order, use factor levels:

mat[order(factor(crit$TYPE, levels = c('Dog', 'Cat', 'Other'))), 
    order(factor(crit$TYPE, levels = c('Dog', 'Cat', 'Other')))]
# 
#   A F B C E D
# A 2 6 5 0 3 1
# F 0 9 0 1 7 1
# B 5 9 0 0 5 1
# C 0 1 0 0 0 0
# E 3 6 1 5 1 2
# D 6 4 1 1 4 3

这篇关于按条件对R矩阵的行和列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆