如何在R中订购双向表

时间:2013-09-28 16:36:07

标签: r

我使用以下命令在R中创建了一个表:

ExamSex<-table(Exam, Sex)

我现在想要通过Exam的值对表进行排序,并创建一个带有排序值的新表。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

table基本上是matrix,因此您可以使用它与处理矩阵的方式非常相似。

当您对两个项目使用table时,rownames将成为第一个项目的唯一值,而colnames将成为第二个项目的唯一值。

以下是一个例子:

out <- table(state.division, state.region)
out
#                     state.region
# state.division       Northeast South North Central West
#   New England                6     0             0    0
#   Middle Atlantic            3     0             0    0
#   South Atlantic             0     8             0    0
#   East South Central         0     4             0    0
#   West South Central         0     4             0    0
#   East North Central         0     0             5    0
#   West North Central         0     0             7    0
#   Mountain                   0     0             0    8
#   Pacific                    0     0             0    5
unique(state.division)
# [1] East South Central Pacific            Mountain           West South Central
# [5] New England        South Atlantic     East North Central West North Central
# [9] Middle Atlantic   
# 9 Levels: New England Middle Atlantic South Atlantic ... Pacific
unique(state.region)
# [1] South         West          Northeast     North Central
# Levels: Northeast South North Central West

因此,如果我们想按第一个值排序,我们需要按照您的表的rownames订购:

out[order(rownames(out)), ]
#                     state.region
# state.division       Northeast South North Central West
#   East North Central         0     0             5    0
#   East South Central         0     4             0    0
#   Middle Atlantic            3     0             0    0
#   Mountain                   0     0             0    8
#   New England                6     0             0    0
#   Pacific                    0     0             0    5
#   South Atlantic             0     8             0    0
#   West North Central         0     0             7    0
#   West South Central         0     4             0    0