2013-03-27 123 views
4

我從0到39以下因素如何,他們現在下令:重新排序因素在數據幀

> levels(items$label) 
[1] "0" "1" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" 
[13] "2" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "3" 
[25] "30" "31" "32" "33" "34" "35" "36" "37" "38" "39" "4" "5" 
[37] "6" "7" "8" "9" 

如何重新排序按數字順序,顯示目的?我不想改變數據框的含義。

更新:如何更新原始數據框items,排序後的因子爲labels?這不應該實質性地改變數據框;我只是希望這些因素在後續的操作中以正確的順序出來。

回答

4
sorted_labels <- paste(sort(as.integer(levels(items$label)))) 

給出:

[1] "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" 
[13] "12" "13" "14" "15" "16" "17" "18" "19" "20" "21" "22" "23" 
[25] "24" "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35" 
[37] "36" "37" "38" "39" 

或(如https://stackoverflow.com/a/15665655/109618提到):

sorted_labels <- order(levels(items$label)) - 1 
# order by itself is a 1-based vector 
# using `- 1` gives a 0-based vector 

每更新的問題,這將更新數據幀:

items$label <- factor(items$label, levels = sorted_labels) 
1

如果所有的整數都是公關的ESENT,那麼你可以簡單地使用order

order(levels(items$label)) - 1 # where the minus 1 is for starting from 0 

如果不是所有的整數都存在,那麼你必須使用as.numeric,就像你擁有了它。

+0

這更簡潔。根據我更新的問題,我如何更新排序後的原始數據框? – 2013-03-27 18:31:29

+0

@DavidJames對我來說聽起來像一個不同的問題;) – 2013-03-27 19:45:06

+0

@DavidJames,你需要詳細說明你的意思是什麼「更新」你想要的最終結果是什麼? – 2013-03-27 19:45:40