如何使用列表指定排序顺序?

时间:2011-12-08 00:25:02

标签: r sorting

原谅我的无知,但我在排序数据框时遇到了麻烦。我想在排序时指定一个有序的列表,如c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"),以便数据框按列表的顺序排序。

在这个例子中,我想从

开始
    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")

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

Dunno为什么,但这没有改变我的数据帧的顺序。

相反,以下代码执行了:

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

请注意,您只需更改df中行的原始顺序。