【问题标题】:How to subset your dataframe to only keep the first duplicate? [duplicate]如何对您的数据框进行子集化以仅保留第一个副本? [复制]
【发布时间】:2018-08-27 11:48:55
【问题描述】:

我有一个包含多个变量的数据框,我对如何对其进行子集化感兴趣,以便它只包含第一个重复项。

    >head(occurrence)
    userId        occurrence  profile.birthday profile.gender postDate count
    1 100469891698         6               47         Female 583 days     0
    2 100469891698         6               47         Female  55 days     0
    3 100469891698         6               47         Female 481 days     0
    4 100469891698         6               47         Female 583 days     0
    5 100469891698         6               47         Female 583 days     0
    6 100469891698         6               47         Female 583 days     0

在这里您可以看到数据框。 'occurrence' 列计算相同 userId 出现的次数。我尝试了以下代码来删除重复项:

    occurrence <- occurrence[!duplicated(occurrence$userId),]

但是,这种方式会删除“随机”重复项。我想保留 postDate 最旧的数据。例如,第一行应该是这样的:

   userId        occurrence  profile.birthday profile.gender postDate count
  1 100469891698         6               47         Female 583 days     0

感谢您的帮助!

【问题讨论】:

  • 欢迎来到 Stack Overflow。 duplicated 标记为 TRUE 除第一个以外的所有出现(无随机性)。但是,您的数据可能不会按postDate 排序(递减),因此您需要在通话之前对其进行排序,或者使用按postDate 分组的替代方式,每个userId 只保留一行(您可以找到examples of codes to do that in SO Q&A)

标签: r duplicates subset


【解决方案1】:

您是否尝试过像这样先订购:

occurrence <- occurrence[order(occurrence$userId, occurrence$postDate, decreasing=TRUE),]
occurrenceClean <- occurrence[!duplicated(occurrence$userId),]
occurrenceClean

【讨论】:

    【解决方案2】:

    您可以为此使用 dplyr,并在过滤最大 postDate 后,使用 distinct(唯一)删除所有重复的行。当然,如果最大 postDate 的行存在差异,您将获得所有这些记录。

    occurrence <- occurrence %>% 
      group_by(userId) %>% 
      filter(postDate == max(postDate)) %>% 
      distinct
    
      occurence
    # A tibble: 1 x 6
    # Groups:   userId [1]
            userId occurrence profile.birthday profile.gender postDate count
             <dbl>      <int>            <int> <chr>          <chr>    <int>
    1 100469891698          6               47 Female         583 days     0
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2021-03-23
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多