user1424739
user1424739

Reputation: 13755

merge adjacent integers into ranges?

I want to merge adjacent integers into ranges.

For example, suppose the input is the following.

R> c(1,2,3, 5,6, 9,10,11,12)

The output should be a matrix of the range boundary. The result for the example should be.

rbind(
c(1, 3)
, c(5, 6)
, c(9,12)
)

How to perform this operation in an efficient way? I suppose that vectorized functions should be called to speed things up, as for-loop, although can solve the problem, is not efficient.

Upvotes: 1

Views: 49

Answers (1)

jay.sf
jay.sf

Reputation: 73592

Split at cumsum where differences are unequal to 1 and apply range using by for instance.

x <- c(1, 2, 3, 5, 6, 9, 10, 11, 12)

do.call(rbind, by(x, cumsum(c(1, diff(x)) != 1), range))
#   [,1] [,2]
# 0    1    3
# 1    5    6
# 2    9   12

Upvotes: 2

Related Questions