[英]How do I remove duplicates based on three columns, but I keep the row with the highest number in the specific column using R?
[英]remove duplicates but keep the row based on a specific column
我有一個大型數據集,它是通過組合來自多個來源的數據而構建的。 因此,有許多行是重復的。 我知道如何使用 dplyr 和 distinct 刪除重復項,但我希望它始終根據單元格(源文件)中的特定值保留行。 本質上,我們對我們更喜歡哪些來源進行了排名。 下面是一個非常簡化的數據集,用作示例:
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”行。
我很感激有關如何執行最后一步以優先考慮保留重復行的原始行的任何建議。
非常感謝,阿曼達
由於您的優先級恰好按字母倒序排列,因此在這種情況下,您可以簡單地在distinct()
調用之前arrange(desc(source))
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
不同的尊重順序。 因此,由於您的標准是按字母順序排列的*,您可以像這樣簡單地做到這一點:
mydata |>
arrange(desc(source)) |>
distinct(species, count, year, .keep_all= TRUE)
.* 在其他情況下,您需要使用訂單創建一個變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.