【问题标题】:Eliminating duplicates in R using a specific criterion [duplicate]使用特定标准消除 R 中的重复项 [重复]
【发布时间】:2020-07-08 23:00:41
【问题描述】:

我正在处理一个包含两个感兴趣变量的大型数据框:id 和日期。我想消除具有重复 id 的每一行,但我想保留最新日期的行。我一直在使用dplyr::distinct,但我不知道如何添加这个日期条件。

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:
    set.seed(42)
    dat <- tibble(id=sample(LETTERS[1:3], size=100, replace=TRUE), date=sample(10, size=100, replace=TRUE))
    dat
    # # A tibble: 100 x 2
    #    id     date
    #    <chr> <int>
    #  1 A         8
    #  2 A         7
    #  3 A         6
    #  4 A         1
    #  5 B         5
    #  6 B         9
    #  7 B         7
    #  8 A        10
    #  9 C        10
    # 10 C        10
    # # ... with 90 more rows
    
    dat %>%
      group_by(id) %>%
      slice(which.max(date))
    # # A tibble: 3 x 2
    # # Groups:   id [3]
    #   id     date
    #   <chr> <int>
    # 1 A        10
    # 2 B        10
    # 3 C        10
    

    【讨论】:

      【解决方案2】:

      一种使用 janitor::get_dupes 的方法

      library(tidyverse)
      library(janitor)
      #> 
      #> Attaching package: 'janitor'
      #> The following objects are masked from 'package:stats':
      #> 
      #>     chisq.test, fisher.test
      
      set.seed(42)
      dat <- tibble(id=sample(LETTERS[1:3], size=100, replace=TRUE), date=sample(10, size=100, replace=TRUE))
      dat
      #> # A tibble: 100 x 2
      #>    id     date
      #>    <chr> <int>
      #>  1 A         8
      #>  2 A         7
      #>  3 A         6
      #>  4 A         1
      #>  5 B         5
      #>  6 B         9
      #>  7 B         7
      #>  8 A        10
      #>  9 C        10
      #> 10 C        10
      #> # … with 90 more rows
      
      dat %>% 
        get_dupes(id) %>% 
        group_by(id) %>% 
        arrange(desc(date)) %>% 
        slice(1)
      #> # A tibble: 3 x 3
      #> # Groups:   id [3]
      #>   id    dupe_count  date
      #>   <chr>      <int> <int>
      #> 1 A             40    10
      #> 2 B             39    10
      #> 3 C             21    10
      

      reprex package (v0.3.0) 于 2020 年 7 月 8 日创建

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 2020-08-13
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2015-09-30
        • 1970-01-01
        • 2020-12-31
        • 2016-05-16
        相关资源
        最近更新 更多