0

How to remove successive duplicate rows based on first columnv1?

v1  v2
1   A
1   A
2   B
3   B
1   A
1   A
2   A
2   B

Desired Output:

v1 v2
1  A
2  B
3  B
1  A
2  A
M--
  • 25,431
  • 8
  • 61
  • 93
Cina
  • 9,759
  • 4
  • 20
  • 36

1 Answers1

2

Here's a way with rle in base R -

x <- c(1,1,2,3,1,1,2,2)

ind <- with(rle(x), sequence(lengths) == 1)

x[ind]

[1] 1 2 3 1 2

Another way would be by checking lag values -

ind <- c(TRUE, x[-length(x)] != x[-1])

x[ind]

[1] 1 2 3 1 2
Shree
  • 10,835
  • 1
  • 14
  • 36