R - delete consecutive (ONLY) duplicates

后端 未结 4 585
长情又很酷
长情又很酷 2020-12-11 06:55

I need to eliminate rows from a data frame based on the repetition of values in a given column, but only those that are consecutive. For example, for the following data fram

4条回答
  •  鱼传尺愫
    2020-12-11 07:03

    Here is a data.table solution. The trick is to create a shifted version of x with the shift function and compare it with x

    library(data.table)
    dattab <- as.data.table(df)
    dattab[x != shift(x = x, n = 1, fill = -999, type = "lead")] # edited to add closing )
    

    This way you compare each value of x with its immediately following value and throw out where they match. Make sure to set fill to something that is not in x in order for correct handling of the last value.

提交回复
热议问题