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
2条答案
按热度按时间hc8w905p1#
table
本质上是matrix
,因此您可以以与矩阵相同的方式使用它。当您对两个项目使用
table
时,rownames
将成为第一个项目的唯一值,colnames
将成为第二个项目的唯一值。下面是一个示例:
因此,如果我们想按第一个值排序,我们需要按表的
rownames
排序:jjjwad0x2#
有些用户可能希望通过降低总行频率对行进行排序,通过降低总列频率对列进行排序。这相当于在SAS中使用
proc freq
创建双向表时设置order=freq
。在R中可以这样做:或者,以更紧凑的函数形式,使用管道操作符(需要
magrittr
包),