本文介绍了按顺序删除/折叠连续的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

a a a b c c d e a a b b b e e d d

要求的结果应该是

a b c d e a b e d

这意味着没有两个连续的行应该具有相同的值.如何在不使用循环的情况下完成.

It means no two consecutive rows should have same value. How it can be done without using loop.

由于我的数据集非常庞大,执行循环需要很多时间.

As my data set is quite huge, looping is taking lot of time to execute.

数据帧结构如下

a 1
a 2
a 3
b 2
c 4
c 1
d 3
e 9
a 4
a 8
b 10
b 199
e 2
e 5
d 4
d 10

结果:

a 1
b 2
c 4
d 3
e 9
a 4
b 10
e 2
d 4

它应该删除整行.

推荐答案

一种简单的方法是使用rle:

One easy way is to use rle:

这是您的示例数据:

x <- scan(what = character(), text = "a a a b c c d e a a b b b e e d d")
# Read 17 items

rle 返回一个带有两个值的 list:运行长度(lengths"),以及为该运行重复的值(").

rle returns a list with two values: the run length ("lengths"), and the value that is repeated for that run ("values").

rle(x)$values
# [1] "a" "b" "c" "d" "e" "a" "b" "e" "d"

更新:对于 data.frame

如果您正在使用 data.frame,请尝试以下操作:

## Sample data
mydf <- data.frame(
  V1 = c("a", "a", "a", "b", "c", "c", "d", "e",
         "a", "a", "b", "b", "e", "e", "d", "d"),
  V2 = c(1, 2, 3, 2, 4, 1, 3, 9,
         4, 8, 10, 199, 2, 5, 4, 10)
)

## Use rle, as before
X <- rle(mydf$V1)
## Identify the rows you want to keep
Y <- cumsum(c(1, X$lengths[-length(X$lengths)]))
Y
# [1]  1  4  5  7  8  9 11 13 15
mydf[Y, ]
#    V1 V2
# 1   a  1
# 4   b  2
# 5   c  4
# 7   d  3
# 8   e  9
# 9   a  4
# 11  b 10
# 13  e  2
# 15  d  4

更新 2

data.table"包有一个函数 rleid 可以让你很容易地做到这一点.使用上面的 mydf,尝试:


Update 2

The "data.table" package has a function rleid that lets you do this quite easily. Using mydf from above, try:

library(data.table)
as.data.table(mydf)[, .SD[1], by = rleid(V1)]
#    rleid V2
# 1:     1  1
# 2:     2  2
# 3:     3  4
# 4:     4  3
# 5:     5  9
# 6:     6  4
# 7:     7 10
# 8:     8  2
# 9:     9  4

这篇关于按顺序删除/折叠连续的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 03:23