I created a table in R using the following command:
ExamSex<-table(Exam, Sex)
I want to now sort the table by values of Exam, and create a new table with sorted values. How can I do that?
I created a table in R using the following command:
ExamSex<-table(Exam, Sex)
I want to now sort the table by values of Exam, and create a new table with sorted values. How can I do that?
A table
is essentially a matrix
, so you can work with it in much the same way you would work with a matrix.
When you use table
on two items, the rownames
become the unique values of the first item and the colnames
become the unique values of the second item.
Here's an example:
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
Thus, if we wanted to order by the first value, we would need to order by the rownames
of your table:
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