如何删除基于三列的重复项,但使用R保留特定列中数字最高的行



我有一个看起来像这样的数据集:

Unique Id|Class Id|Version Id
501        1          1
602        3          1
602        3          1
405        2          1
305        2          3
305        2          2
305        1          1
305        2          1
509        1          1
501        2          1
501        3          1
501        3          2
602        2          1
602        1          1
405        1          1

如果我要运行脚本,剩下的条目应该是:

Unique Id|Class Id|Version Id
501        1          1
602        3          1
405        2          1
305        2          3
305        1          1
509        1          1
501        2          1
501        3          2
602        2          1
602        1          1
405        1          1

请注意,选择了唯一id:501类id:3和版本id:2,因为它具有最高的版本id。请注意,删除了唯一id:602类id:3,版本id:1,因为它从头到尾完全相同。

基本上,我希望脚本删除基于三列的所有重复项,并保留具有最高版本id的行。

我们可以在UniqueID列上使用rleid,并在通过"唯一Id"上的rleidClass Id分组后进行slice_max

library(dplyr)
library(data.table)
data %>%      
group_by(grp = rleid(`Unique Id`), `Class Id`) %>% 
slice_max(`Version Id`) %>%
ungroup %>%
select(-grp) %>%
distinct

-输出

# A tibble: 11 x 3
#   `Unique Id` `Class Id` `Version Id`
#         <int>      <int>        <int>
# 1         501          1            1
# 2         602          3            1
# 3         405          2            1
# 4         305          1            1
# 5         305          2            3
# 6         509          1            1
# 7         501          2            1
# 8         501          3            2
# 9         602          1            1
#10         602          2            1
#11         405          1            1

或者,如果我们不必将具有相邻块的Unique Id视为一个

data %>%
group_by(`Unique Id`, `Class Id`) %>%
slice_max(`Version Id`) %>% 
ungroup %>% 
distinct

或使用base R

ind <- with(rle(data$`Unique Id`), rep(seq_along(values), lengths))
data1 <- data[order(ind, -data$`Version Id`),]
data1[!duplicated(cbind(ind, data1$`Class Id`)),]

数据

data <- structure(list(`Unique Id` = c(501L, 602L, 602L, 405L, 305L, 
305L, 305L, 305L, 509L, 501L, 501L, 501L, 602L, 602L, 405L), 
`Class Id` = c(1L, 3L, 3L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 3L, 
3L, 2L, 1L, 1L), `Version Id` = c(1L, 1L, 1L, 1L, 3L, 2L, 
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L)), class = "data.frame", 
row.names = c(NA, 
-15L))

如果顺序无关紧要,那么我们可以对数据进行重新排序,使更高版本的ID位于顶部,然后删除重复的条目。

df <- df[order(df[,1], df[,2], -df[,3]),]
df <- df[!duplicated(df[,-3]),]
df
Unique Id Class Id Version Id
7        305        1          1
5        305        2          3
15       405        1          1
4        405        2          1
1        501        1          1
10       501        2          1
12       501        3          2
9        509        1          1
14       602        1          1
13       602        2          1
2        602        3          1

最新更新