2014-06-26 25 views
1

我有以下格式的數據幀:如何使用字符串等整數對數據框列進行排序?

<year joined>, <win streak>, <points> 
2012   0-10 days  xxx 
2013   0-10 days  xxx 
2014   0-10 days  xxx 
2012   1-2 years  xxx 
2013   1-2 years  xxx 
2014   1-2 years  xxx 
2012   11-50 days xxx 
2013   11-50 days xxx 
2014   11-50 days xxx 
...    

的問題是,因爲字符串排序,使「1 - 2年」之前「11-50天」中的「連勝」列排序不正確。

什麼是訂購這個數據框的一種情感方式,所以加入的年份仍然是從2012年到2014年的順序,但是連勝組按照升序排列,儘管它們是括號,並且不能表示作爲真正的整數。

回答

3

生成假數據

z = as.factor(sample(c("0-10 Days", "11-50 Days", "1-2 Years"), 20, replace = TRUE)) 
z 
    [1] 0-10 Days 0-10 Days 11-50 Days 0-10 Days 0-10 Days 11-50 Days 11-50 Days 1-2 Years 
    [9] 11-50 Days 1-2 Years 0-10 Days 11-50 Days 11-50 Days 0-10 Days 1-2 Years 11-50 Days 
    [17] 1-2 Years 1-2 Years 0-10 Days 0-10 Days 

定義級別

levels(z) = c("0-10 Days", "11-50 Days", "1-2 Years") 
sort(z) 
    [1] 0-10 Days 0-10 Days 0-10 Days 0-10 Days 0-10 Days 0-10 Days 0-10 Days 0-10 Days 
    [9] 11-50 Days 11-50 Days 11-50 Days 11-50 Days 11-50 Days 11-50 Days 11-50 Days 1-2 Years 
    [17] 1-2 Years 1-2 Years 1-2 Years 1-2 Years 
    Levels: 0-10 Days 11-50 Days 1-2 Years 

如果你想跟蹤的時候,你可以用POSIXlt類代替。

相關問題