2011-12-08 114 views
3

原諒我的無知,但我在排序數據框時遇到了問題。我想在排序時指定一個有序列表,如c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"),以便數據框按列表順序排序。如何使用R中的列表指定排序順序?

在這個例子中,我想先從

Day Present Count 
    Fri No 164 
    Fri Yes 131 
    Mon No 142 
    Mon Yes 174 
    Sat No 39 
    Sat Yes 26 
    Sun No 44 
    Sun Yes 39 
    Thu No 191 
    Thu Yes 192 
    Tue No 184 
    Tue Yes 214 
    Wed No 343 
    Wed Yes 255 

,並結束與

Day Present Count 
    Mon No 142 
    Mon Yes 174 
    Tue No 184 
    Tue Yes 214 
    Wed No 343 
    Wed Yes 255 
    Thu No 191 
    Thu Yes 192 
    Fri No 164 
    Fri Yes 131 
    Sat No 39 
    Sat Yes 26 
    Sun No 44 
    Sun Yes 39 

我已經試過perday[do.call(order, perday[c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")]),]但我得到「選擇未定義列」。如果字符向量中有14個條目,我也會得到相同的錯誤,所以我現在非常困惑。

這裏的dput:

perday<-structure(list(dayofweek = c("Fri", "Fri", "Mon", "Mon", "Sat", 
"Sat", "Sun", "Sun", "Thu", "Thu", "Tue", "Tue", "Wed", "Wed" 
), Attended = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L), .Label = c("No", "Yes"), class = "factor"), 
    nrow = c(164L, 131L, 142L, 174L, 39L, 26L, 44L, 39L, 191L, 
    192L, 184L, 214L, 343L, 255L)), .Names = c("dayofweek", "Attended", 
"nrow"), row.names = c(NA, -14L), class = "data.frame") 

回答

8

您可以

perday[order(factor(perday$dayofweek,levels=c(c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")))),] 

這給

dayofweek Attended nrow 
3  Mon  No 142 
4  Mon  Yes 174 
11  Tue  No 184 
12  Tue  Yes 214 
13  Wed  No 343 
14  Wed  Yes 255 
9  Thu  No 191 
10  Thu  Yes 192 
1  Fri  No 164 
2  Fri  Yes 131 
5  Sat  No 39 
6  Sat  Yes 26 
7  Sun  No 44 
8  Sun  Yes 39 
+2

啊,必須讓他們的因素,然後指定的水平。現在我已經開始在我的導入中設置stringsAsFactors = FALSE,我真的開始學習什麼因素了! –

+0

太好了。這使生活變得輕鬆。 – saudic

0

說不上爲什麼這樣做 「內聯」,但並沒有改變的順序我的數據幀。

相反,下面的代碼所做的:

dfordered=df[c(1,2,3,9,5,6,8,10,11,4,7),] 

注意,你只需要改變你的DF行的原始順序。