【问题标题】:Subset to remove duplicate id and condition删除重复 id 和条件的子集
【发布时间】:2021-11-29 10:27:26
【问题描述】:

如果这是我的数据集

Id   Weight   Category
1    10.2     Pre
1    12.1     Post
2    11.3     Post
3    12.9     Pre
4    10.3     Post
4    12.3     Pre
5    11.8     Pre

我如何删除也是 Category=Pre 的重复 ID。我的最终预期数据集将是

Id   Weight   Category

1    12.1     Post
2    11.3     Post
3    12.9     Pre
4    10.3     Post
5    11.8     Pre

【问题讨论】:

    标签: r dataframe duplicates subset


    【解决方案1】:

    您可以整理数据,然后使用distinct。

    library(dplyr)
    
    df %>% arrange(Id, Category) %>% distinct(Id, .keep_all = TRUE)
    
    #  Id Weight Category
    #1  1   12.1     Post
    #2  2   11.3     Post
    #3  3   12.9      Pre
    #4  4   10.3     Post
    #5  5   11.8      Pre
    

    这是因为'Pre' > 'Post'。

    【讨论】:

    • 我的真实数据集中有一个date 列,当我运行您的解决方案时,它抛出一个错误`date_valideate() 中的内部错误:具有未知类型字符的损坏日期。`
    • 我看不出为什么日期列会改变答案中的任何内容。尝试重新启动 R 或提供可重现的示例。
    【解决方案2】:

    使用by,将dat 拆分为Id 并选择Post,然后选择rbind 结果。

    do.call(rbind, by(dat, dat$Id, function(x) 
      if (nrow(x) == 2)  x[x$Category == 'Post', ] else x))
    #   Id Weight Category
    # 1  1   12.1     Post
    # 2  2   11.3     Post
    # 3  3   12.9      Pre
    # 4  4   10.3     Post
    # 5  5   11.8      Pre
    

    数据:

    dat <- read.table(header=T, text='
                      Id   Weight   Category
    1    10.2     Pre
    1    12.1     Post
    2    11.3     Post
    3    12.9     Pre
    4    10.3     Post
    4    12.3     Pre
    5    11.8     Pre
                      ')
    

    【讨论】:

      【解决方案3】:

      我们可以在使用first() 进行分组和排列之后使用filter,因为Post 在Pre 之前:

      df %>% 
        group_by(Id) %>% 
        arrange(Id, Category) %>% 
        filter(Category ==first(Category)) 
      

      输出:

           Id Weight Category
        <int>  <dbl> <chr>   
      1     1   12.1 Post    
      2     2   11.3 Post    
      3     3   12.9 Pre     
      4     4   10.3 Post    
      5     5   11.8 Pre    
      

      【讨论】:

        【解决方案4】:

        使用来自base R的subset

        subset(df[with(df, order(Id, Category == 'Pre')),], !duplicated(Id))
          Id Weight Category
        2  1   12.1     Post
        3  2   11.3     Post
        4  3   12.9      Pre
        5  4   10.3     Post
        7  5   11.8      Pre
        

        数据

        df <- structure(list(Id = c(1L, 1L, 2L, 3L, 4L, 4L, 5L), Weight = c(10.2, 
        12.1, 11.3, 12.9, 10.3, 12.3, 11.8), Category = c("Pre", "Post", 
        "Post", "Pre", "Post", "Pre", "Pre")), class = "data.frame", 
        row.names = c(NA, 
        -7L))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-01-24
          • 1970-01-01
          • 2021-10-21
          • 2017-08-29
          • 2018-09-24
          • 1970-01-01
          • 2022-01-02
          • 1970-01-01
          相关资源
          最近更新 更多