【问题标题】:Remove duplicates based on next row [duplicate]根据下一行删除重复项[重复]
【发布时间】:2019-01-11 04:46:40
【问题描述】:

我是 R 新手。我希望删除 df$x = "string" AND the next row = the same string

的数据框中的重复行

所以说我有这个专栏

1. String - remove 2. String 3. A 4. A 5. A 6. String - remove 7. String - remove 8. String 9. A 10. A

我想要的结果是

2. String 3. A 4. A 5. A 8. String 9. A 10. A

【问题讨论】:

    标签: r duplicates shift


    【解决方案1】:

    我们可以使用dplyr 中的lead 并删除当前行和下一行是“字符串”的行。

    library(dplyr)
    
    df %>%
      filter(!(V1 == "String" & lead(V1) == "String"))
    
    #      V1
    #1 String
    #2      A
    #3      A
    #4 String
    #5      A
    

    使用base R,我们可以做到

    df[!((df$V1 == "String") & c(df$V1[-1], NA) == "String"),,drop = FALSE]
    
    #      V1
    #2 String
    #3      A
    #4      A
    #7 String
    #8      A
    

    数据

    df <- structure(list(V1 = c("String", "String", "A", "A", "String", 
    "String", "String", "A")), .Names = "V1", row.names = c(NA, -8L
     ), class = "data.frame")
    

    【讨论】:

    • 是的!我使用了基本 R 选项 :)
    【解决方案2】:

    我们可以使用duplicatedrleid 创建一个逻辑索引来对行进行子集化

    library(data.table)
    setDT(df)[!(duplicated(rleid(V1)) & V1 == 'String')]
    #       V1
    #1: String
    #2:      A
    #3:      A
    #4: String
    #5:      A
    

    数据

    df <- structure(list(V1 = c("String", "String", "A", "A", "String", 
    "String", "String", "A")), row.names = c(NA, -8L), class = "data.frame")
    

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      相关资源
      最近更新 更多