簡體   English   中英

排除后續重復的行

[英]Exclude subsequent duplicated rows

我想排除所有重復的行。 但是,只有當它們是后續行時才必須如此。 遵循一個代表性的例子:

我的輸入df

    df <- "NAME   VALUE 
    Prb1  0.05
    Prb2  0.05
    Prb3  0.05
    Prb4  0.06
    Prb5  0.06
    Prb6  0.01
    Prb7  0.10
    Prb8  0.05"

df <- read.table(text=df, header=T)

我的預期outdf

outdf <- "NAME   VALUE 
Prb1  0.05
Prb4  0.06
Prb6  0.01
Prb7  0.10
Prb8  0.05"

outdf <- read.table(text=df, header=T)

rle()是一個很好的函數,它可以識別相同值的運行,但是將它的輸出轉換為可用的形式可能會很麻煩。 這是一個相對無痛的咒語,適用於你的情況。

df[sequence(rle(df$VALUE)$lengths) == 1, ]
#   NAME VALUE
# 1 Prb1  0.05
# 4 Prb4  0.06
# 6 Prb6  0.01
# 7 Prb7  0.10
# 8 Prb8  0.05

可能有很多方法可以解決這個問題,我會嘗試使用data.table devel版本中的 rleid/unique組合

library(data.table) ## v >= 1.9.5
unique(setDT(df)[, indx := rleid(VALUE)], by = "indx")
#    NAME VALUE indx
# 1: Prb1  0.05    1
# 2: Prb4  0.06    2
# 3: Prb6  0.01    3
# 4: Prb7  0.10    4
# 5: Prb8  0.05    5

或者從評論中提出一些很好的建議:

僅使用新的shift功能

setDT(df)[VALUE != shift(VALUE, fill = TRUE)]

或者使用duplicated結合rleid

setDT(df)[!duplicated(rleid(VALUE)), ]

這個怎么樣:

> df[c(T, df[-nrow(df),-1] != df[-1,-1]), ]
  NAME VALUE
1 Prb1  0.05
4 Prb4  0.06
6 Prb6  0.01
7 Prb7  0.10
8 Prb8  0.05

這里, df[-nrow(df),-1] != df[-1,-1]查找包含不同值的連續行對,其余代碼從數據幀中提取它們。

我會使用類似於@NPE的解決方案

df[c(TRUE,abs(diff(df$VALUE))>1e-6),]

當然,您可以使用任何其他容差級別( 1e-6除外)。

我剛才遇到了這個很好的函數,它首先根據指定的變量標記行:

  isFirst <- function(x,...) {
      lengthX <- length(x)
      if (lengthX == 0) return(logical(0))
      retVal <- c(TRUE, x[-1]!=x[-lengthX])
      for(arg in list(...)) {
          stopifnot(lengthX == length(arg))
          retVal <- retVal | c(TRUE, arg[-1]!=arg[-lengthX])
      }
      if (any(missing<-is.na(retVal))) # match rle: NA!=NA
          retVal[missing] <- TRUE
      retVal
  }

將其應用於您的數據會給出:

> df$first <- isFirst(df$VALUE)
> df
  NAME VALUE first
1 Prb1  0.05  TRUE
2 Prb2  0.05 FALSE
3 Prb3  0.05 FALSE
4 Prb4  0.06  TRUE
5 Prb5  0.06 FALSE
6 Prb6  0.01  TRUE
7 Prb7  0.10  TRUE
8 Prb8  0.05  TRUE

然后,您可以在第一列上進行重復數據刪除以獲得預期輸出。

我發現這在過去非常有用,特別是來自SAS背景,這很容易做到。

已有很多好的答案,這里是dplyr版本:

filter(df,VALUE!=lag(VALUE,default=df$VALUE[1]+1))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM