【问题标题】:Remove consecutive duplicate entries删除连续的重复条目
【发布时间】:2013-07-15 09:17:51
【问题描述】:

如何删除 R 中连续的重复条目?我认为with 可以使用但想不出如何使用它。举例说明:

read.table(text = "
   a        t1
   b        t2
   b        t3
   b        t4
   c        t5
   c        t6
   b        t7
   d        t8")

样本数据:D

    events    time
       a        t1
       b        t2
       b        t3
       b        t4
       c        t5
       c        t6
       b        t7
       d        t8

要求的结果:

     events     time
       a        t1
       b        t4
       c        t6
       b        t7
       d        t8

`

【问题讨论】:

    标签: r duplicates with-statement


    【解决方案1】:

    还有一个,假设您的data.frmae 被命名为d

    d[cumsum(rle(as.numeric(d[,1]))$lengths),]
      V1 V2
    1  a t1
    4  b t4
    6  c t6
    7  b t7
    8  d t8
    

    【讨论】:

    • +1 这也是我的答案。我阅读了 OP 问题,当他们说 删除连续重复的条目时,我想使用 cumsum( rle( df$Event )$lengths ) - rle( df$Event )$lengths + 1 来获取每个条目中的第一个
    • +1,绝对比我的 rlemapplysplittaildo.call、...
    【解决方案2】:

    编辑:不完全正确,因为它只显示一个 b 行。 也可以使用duplicated()函数

    x <- read.table(text = "    events    time
       a        t1
       b        t2
       b        t3
       b        t4
       c        t5
       c        t6
       d        t7", header = TRUE)
    #Making sure the data is correctly ordered!
    x <- x[order(x[,1], x[,2]), ]      
    x[!duplicated(x[,1], fromLast=TRUE), ]
    

    【讨论】:

    • 这很接近,但它并没有完全给出 OP 的预期结果。虽然我从来不知道fromLast=TRUE - 非常整洁。
    • 天哪!有两个 b 行!
    【解决方案3】:

    在基础 R 中使用 split-apply-combine 的解决方案通过 tail 函数工作,该函数返回最后一个元素,rlemapply 结合创建一个 events 的新向量,保留顺序事件重现的情况:

    x <- read.table(text = "    events    time
           a        t1
           b        t2
           b        t3
           b        t4
           c        t5
           c        t6
           b        t7
           d        t8", header = TRUE)
    
    
    # create vector of new.events (i.e., preserve reappearing objects)
    occurences <- rle(as.character(x$events))[["lengths"]]
    new.events <- unlist(mapply(rep, x = letters[seq_along(occurences)], times = occurences))
    
    # split into sublists per event
    s1 <- split(x, list(new.events))
    
    # get last element from list
    s2 <- lapply(s1, tail, n = 1)
    
    # combine again
    do.call(rbind, s2)
    

    这会产生所需的输出。

    【讨论】:

    • 感谢您的帮助,但问题略有变化。使用tail 的顺序是否也保持不变?我试过了,它按字母顺序对事件进行排序。
    【解决方案4】:

    为了更好的衡量,使用headtail

    dat[with(dat,c(tail(events,-1) != head(events,-1),TRUE)),]
    
      events time
    1      a   t1
    4      b   t4
    6      c   t6
    7      b   t7
    8      d   t8
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-05
      • 2021-12-20
      • 2018-12-01
      • 1970-01-01
      • 2020-03-30
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多