删除重复项,但保留基于特定列的行

问题描述 投票:0回答:2

我有一个通过组合多个来源的数据构建的大型数据集。因此,有许多行是重复的。我知道如何使用 dplyr 和 unique 删除重复项,但我希望它始终根据单元格(源文件)中的特定值保留行。本质上,我们对我们喜欢的来源进行了排名。下面是一个非常简化的数据集作为示例:

mydata = data.frame (species =c ('myli','myli','myli','myli','myli','stili','stili','stili'),
                     count = c (10,10,15,15,12,10,10,10),
                     year =c(2020,2020,2021,2021,2019,2017,2017,2018),
                     source =c('zd','steam','ted','steam','zd','steam','ted','steam'))
    
    
    mydata

  species count year source
1    myli    10 2020     zd
2    myli    10 2020  steam
3    myli    15 2021    ted
4    myli    15 2021  steam
5    myli    12 2019     zd
6   stili    10 2017  steam
7   stili    10 2017    ted
8   stili    10 2018  steam

我执行以下操作来删除重复项:

library(dplyr)
 
# Remove duplicate rows of the dataframe using 'species', 'count', and 'year' variables
distinct(mydata, species, count, year, .keep_all= TRUE)

  species count year source
1    myli    10 2020     zd
2    myli    15 2021    ted
3    myli    12 2019     zd
4   stili    10 2017  steam
5   stili    10 2018  steam

但是,我想确保存在重复项时保留的行按以下顺序优先考虑“源”:zd > ted > steam,因此最终表如下所示:

  species count year source
1    myli    10 2020     zd
2    myli    15 2021    ted
3    myli    12 2019     zd
4   stili    10 2017    ted
5   stili    10 2018  steam

因此本质上保留原始行“1”、“3”、“5”、“7”和“8”,并删除重复行“2”、“4”和“6”。

我很感激有关如何执行最后一步以优先保留重复行中的原始行的建议。

r dplyr
2个回答
3
投票

由于您的优先级恰好按字母顺序相反,在这种情况下,您只需在

arrange(desc(source))
通话之前
distinct()

mydata %>% 
  arrange(desc(source)) %>% 
  distinct(species,count,year,.keep_all = T)

输出

  species count year source
1    myli    10 2020     zd
2    myli    12 2019     zd
3    myli    15 2021    ted
4   stili    10 2017    ted
5   stili    10 2018  steam

1
投票

明确尊重顺序。因此,由于您的标准是按字母顺序排列的*,您可以像这样简单地做到这一点:

mydata |>
  arrange(desc(source)) |>
  distinct(species, count, year, .keep_all= TRUE)

.* 在其他情况下,您需要使用订单创建一个变量。

© www.soinside.com 2019 - 2024. All rights reserved.