Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if the numbers are continuous in R?

Tags:

r

statistics

I have a range of values

c(1,2,3,4,5,8,9,10,13,14,15)

And I want to find the ranges where the numbers become discontinuous. All I want is this as output:

(1,5)
(8,10)
(13,15)

I need to find break points.

I need to do it in R.

like image 290
Geekuna Matata Avatar asked Apr 15 '14 22:04

Geekuna Matata


2 Answers

Something like this?

x <- c(1:5, 8:10, 13:15) # example data
unname(tapply(x, cumsum(c(1, diff(x)) != 1), range)
# [[1]]
# [1] 1 5
# 
# [[2]]
# [1]  8 10
# 
# [[3]]
# [1] 13 15

Another example:

x <- c(1, 5, 10, 11:14, 20:21, 23)
unname(tapply(x, cumsum(c(1, diff(x)) != 1), range))
# [[1]]
# [1] 1 1
#
# [[2]]
# [1] 5 5
#
# [[3]]
# [1] 10 14
#
# [[4]]
# [1] 20 21
#
# [[5]]
# [1] 23 23
like image 73
Robert Krzyzanowski Avatar answered Sep 24 '22 17:09

Robert Krzyzanowski


x <- c(1:5, 8:10, 13:15)    
rr <- rle(x - seq_along(x))
rr$values <- seq_along(rr$values)
s <- split(x, inverse.rle(rr))
s
# $`1`
# [1] 1 2 3 4 5
# 
# $`2`
# [1]  8  9 10
# 
# $`3`
# [1] 13 14 15

## And then to get *literally* what you asked for:
cat(paste0("(", gsub(":", ",", sapply(s, deparse)), ")"), sep="\n")
# (1,5)
# (8,10)
# (13,15)
like image 32
Josh O'Brien Avatar answered Sep 26 '22 17:09

Josh O'Brien