gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:56:23 26 4
gpt4 key购买 nike

请原谅我的无知,但我在对数据框进行排序时遇到了麻烦。我想指定一个有序列表,如 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")

最佳答案

你可以用“内联”来做

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

关于r - 如何使用列表指定排序顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8424619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com