r - 根据自定义标识符对数据框中的行进行排序
问题描述
我有一个学生姓名和代码标识符(P和V)的数据框
StudName Code ID
John P a1
Sam V a2
John V a3
Alex P a4
Sam P a5
Alex V a6
Stuart P a7
John V a8
我现在要做的是重新排列每个学生的行,其中代码确定优先级。(V -> P)。意思是,对于每个学生,如果他们的代码为 V,那么该行将高于具有 P 的行。
例如,John 同时拥有代码 P 和 V,并且由于V 优先于 P,它将被置于P 之上,因此:
StudName Code ID
John V a3
John V a8
John P a1
生成的数据框将是:
StudName Code ID
John V a3
John V a8
John P a1
Sam V a2
Sam P a5
Alex V a6
Alex P a4
Stuart P a7
因此,对于每个学生,如果他们有一个代码 V,那么 V 将始终排在第一位,然后是 P。
将不胜感激这方面的一些帮助。
编辑 更新示例:拥有多个 Ps 或 Vs 的学生
解决方案
这是一个基本的 R 解决方案
dfout <- df[order(factor(df$StudName, levels = unique(df$StudName)),
factor(df$Code, levels = c("V","P"))),]
这样
> dfout
StudName Code ID
3 John V a3
8 John V a8
1 John P a1
2 Sam V a2
5 Sam P a5
6 Alex V a6
4 Alex P a4
7 Stuart P a7
或者
dfout <- do.call(rbind,
c(make.row.names = F,
lapply(split(df,factor(df$StudName, levels = unique(df$StudName))),
function(x) x[order(x$Code,decreasing = TRUE),])))
这样
> dfout
StudName Code ID
1 John V a3
2 John V a8
3 John P a1
4 Sam V a2
5 Sam P a5
6 Alex V a6
7 Alex P a4
8 Stuart P a7
数据
df <- structure(list(StudName = c("John", "Sam", "John", "Alex", "Sam",
"Alex", "Stuart", "John"), Code = c("P", "V", "V", "P", "P",
"V", "P", "V"), ID = c("a1", "a2", "a3", "a4", "a5", "a6", "a7",
"a8")), class = "data.frame", row.names = c(NA, -8L))
推荐阅读
- c# - 如何使用 Libre Hardware Monitor 库读取 GPU 传感器
- operating-system - 如何为变量分配内存地址?
- node.js - Firestore:使用 AJAX 帖子将一些数字字段增加一个可变数字。Node.js
- winapi - 如何将 Windows API C 字符串指针转换为字符串?
- php - 具有多个元键的 Wordpress 查询不起作用
- android - 导出到 CSV 时进度对话框出现 NullPointerException - Android
- jquery - 我需要对我的 jquery 进行什么更改才能执行过渡效果
- react-native - React Native react-native-sound 在运行时更改声音文件会出现错误“尝试分配给只读属性”
- html - 如何跳过 HTML 列表中的级别?
- r - eval 中的错误(predvars,data,env):找不到对象“值”