如何在R中创建一个双向表

sczxawaw  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(122)

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

ExamSex<-table(Exam, Sex)

现在我想按Exam的值对表进行排序,并使用排序后的值创建一个新表。我怎么能这么做呢?

hc8w905p

hc8w905p1#

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
jjjwad0x

jjjwad0x2#

有些用户可能希望通过降低总行频率对行进行排序,通过降低总列频率对列进行排序。这相当于在SAS中使用proc freq创建双向表时设置order=freq。在R中可以这样做:

ExamSex <- table(Exam, Sex)
ExamSex <- ExamSex[order(rowSums(ExamSex), decreasing = TRUE), ]
ExamSex <- ExamSex[, order(colSums(ExamSex), decreasing = TRUE), ]

或者,以更紧凑的函数形式,使用管道操作符(需要magrittr包),

ordered_twoway <- function(x, y) {
 table(unname(x), unname(y)) %>%
     `[`(order(rowSums(.), decreasing = TRUE), ) %>%
     `[`(, order(colSums(.), decreasing = TRUE))
}

ordered_twoway(Exam, Sex)

相关问题