How to find if the numbers are continuous in R?

做~自己de王妃 提交于 2019-12-21 04:58:24

问题


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.


回答1:


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



回答2:


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)



回答3:


I published seqle which will do this for you in one line. You can load the package cgwtools or search SO for the code, as it's been posted a couple times.




回答4:


Assuming that you don't care about the exact output and are looking for the min and max of each range, you can use diff/cumsum/range as follows:

x  <- c(1:5, 8:10, 13:15)
x. <- c(0, cumsum( diff(x)-1 ) ) 

lapply( split(x, x.), range )


来源:https://stackoverflow.com/questions/23095415/how-to-find-if-the-numbers-are-continuous-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!