【问题标题】:Remove duplicate records with 4 rows each [duplicate]删除重复记录,每行 4 行 [重复]
【发布时间】:2021-05-20 18:19:42
【问题描述】:

我正在尝试从我的数据框中删除重复的元素。

# A tibble: 12 x 3
       g h         i
   <dbl> <chr> <int>
 1     1 a         1
 2     1 b         2
 3     1 c         3
 4     1 d         4
 5     2 a         5
 6     2 b         6
 7     2 c         7
 8     2 d         8
 9     1 a         9
10     1 b        10
11     1 c        11
12     1 d        12

但每个元素都有 4 行。我希望他保持这种状态。

# A tibble: 8 x 3
      g h         i
  <dbl> <chr> <int>
1     1 a         1
2     1 b         2
3     1 c         3
4     1 d         4
5     2 a         5
6     2 b         6
7     2 c         7
8     2 d         8

我尝试了distinct ()unique(),但没有成功。

【问题讨论】:

    标签: r duplicates


    【解决方案1】:

    我们可以在selected 列上使用distinct

    library(dplyr)
    distinct(df1, g, h, .keep_all = TRUE)
    

    -输出

    #  g h i
    #1 1 a 1
    #2 1 b 2
    #3 1 c 3
    #4 1 d 4
    #5 2 a 5
    #6 2 b 6
    #7 2 c 7
    #8 2 d 8
    

    或者duplicated

    df1[!duplicated(df1[c('g', 'h')]),]
    

    数据

    df1 <- structure(list(g = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 
    1L, 1L), h = c("a", "b", "c", "d", "a", "b", "c", "d", "a", "b", 
    "c", "d"), i = 1:12), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
    

    【讨论】:

      【解决方案2】:

      另一种选择是在data.table 对象上使用unique S3 方法:

      library(data.table)
      
      unique(
        data.table(dat),
        by = c('g', 'h')
      )
      
      #    g h i
      # 1: 1 a 1
      # 2: 1 b 2
      # 3: 1 c 3
      # 4: 1 d 4
      # 5: 2 a 5
      # 6: 2 b 6
      # 7: 2 c 7
      # 8: 2 d 8
      

      数据

      dat <- structure(
        list(
          g = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L),
          h = c("a", "b", "c", "d", "a", "b", "c", "d", "a", "b", "c", "d"),
          i = 1:12
          ),
        row.names = c(NA,-12L),
        class = c("tbl_df", "tbl", "data.frame")
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-07
        • 1970-01-01
        • 2021-03-17
        • 2013-06-30
        • 2012-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多