我使用以下命令在 R 中创建了一个表:
ExamSex<-table(Exam, Sex)
我现在想按 Exam 的值对表进行排序,并创建一个具有排序值的新表。我怎样才能做到这一点?
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