0

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

ExamSex<-table(Exam, Sex)

我现在想按 Exam 的值对表进行排序,并创建一个具有排序值的新表。我怎样才能做到这一点?

4

1 回答 1

2

Atable本质上是 a 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
于 2013-09-28T17:08:19.873 回答