Home > Software design >  How to eliminate gaps in a sequence of numbers?
How to eliminate gaps in a sequence of numbers?

Time:08-13

I am an R newbie and am trying to figure out how to remove gaps > 1 in sequences of numbers, but not make changes to sequences if there are no gaps. So for example using dplyr::dense_rank I get these desired results:

> dplyr::dense_rank(c(1, 1, 2, 2, 5))
[1] 1 1 2 2 3

But executing the following gives me these undesired results:

> dplyr::dense_rank(c(2, 2, 2, 2, 2))
[1] 1 1 1 1 1

When I would these results to be:

[1] 2 2 2 2 2

And as another example a sequence of 2,2,5,8 would be condensed to 2,2,3,4; or 5,5,5,10 condenses to 5,5,5,6 etc.

Is there an easy way to do this? With a preference for dplyr if possible!

CodePudding user response:

It looks like you are looking for

## `x` is a vector of integers (can contain negative values)
dplyr::dense_rank(x)   min(x) - 1

or even

## if `x` is non-decreasing
dplyr::dense_rank(x)   x[1] - 1
  • Related