首页 > 解决方案 > 根据自定义标识符对数据框中的行进行排序

问题描述

我有一个学生姓名和代码标识符(PV)的数据框

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

解决方案


这是一个基本的 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))

推荐阅读