2013-09-28 53 views
-1

我使用下面的命令創建一個表R:如何訂購雙向表中的R

ExamSex<-table(Exam, Sex) 

我想現在排序考試的值的表,並創建一個新表與排序值。我怎樣才能做到這一點?

+0

給我們一些數據工作等等,例子,以及迄今爲止所做的。 – Ananta

+0

歡迎來到SO。請爲我們提供一個[可重現的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – sgibb

+0

或許'ExamSex [order(rownames(ExamSex)),]'?默認情況下,我希望「考試」的值最終成爲你的「rownames」,但正如其他人所建議的那樣,顯示一些示例數據,你期望的輸出和你嘗試過的。 – A5C1D2H2I1M1N2O1R2T1

回答

2

A 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