r - 首先根据列表按列对数据框进行排序,然后在另一列中对数字进行升序
问题描述
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')
这个怎么做?
解决方案
我们可以用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)),]
推荐阅读
- c# - 如何使用 Blazor 服务器正确操作 EditContext 中的验证消息
- python - 使用 tensorflow 获取真阳性、假阳性、假阴性和真阴性列表
- c# - 如何获取 Visual Studio UI Elements 的屏幕位置?
- firebase - Firebase - Admin.firestore 与 functions.firestore
- javascript - 如何在同一行放置可更改的 html 元素?
- google-cloud-platform - 无法获取 gcr.io/automl-vision-ondevice/gcloud-container-1.14.0:latest 的 docker 镜像
- excel - 从excel中的按钮打开文件夹
- c - 这个特定的 C 代码片段似乎没有在 Code:Blocks IDE 中构建和运行
- javascript - ESTree AST 定义中的“<:”符号是什么意思?
- java - 为什么我在使用 Spring Boot Application 的邮递员中没有收到错误消息