首页 > 解决方案 > 首先根据列表按列对数据框进行排序,然后在另一列中对数字进行升序

问题描述

set.seed(42)
df <- data.frame(letters=c(rep('data', 5), rep('oh', 5), rep('yeah', 5), rep('silly', 5)),
                 numbers=runif(n = 20, min = 1, max = 10))

我知道我可以按字母 col 字母排序,然后按数字 col 数字排序,如下所示:

 df[with(df, order(letters, numbers)), ]

那很接近,但我想强制字母 col 首先按此顺序排序c('silly', 'data', 'oh', 'yeah')

这个怎么做?

标签: r

解决方案


我们可以用match

df[with(df, order(match(letters, c('silly', 'data', 'oh', 'yeah')), numbers)),]

-输出

 letters  numbers
18   silly 2.057386
19   silly 5.274974
20   silly 6.042995
16   silly 9.460131
17   silly 9.804038
3     data 3.575256
5     data 6.775710
4     data 8.474029
1     data 9.233254
2     data 9.433679
8       oh 2.211999
6       oh 5.671864
9       oh 6.912931
10      oh 7.345583
7       oh 7.629295
14    yeah 3.298859
11    yeah 5.119676
15    yeah 5.160635
12    yeah 7.472010
13    yeah 9.412050

factor或者在订单中levels指定了另一个选项

df[with(df, order(factor(letters, levels = c('silly', 'data', 'oh', 'yeah')), numbers)),]

推荐阅读