Finding groups of contiguous numbers in a list [duplicate]

余生颓废 提交于 2020-01-03 17:07:19

问题


This is a duplicate question to this, except for R rather than Python.

I'd like to identify groups of contiguous (some people call them continuous) integers in a list, where duplicate entries are treated as existing within the same range. Therefore:

myfunc(c(2, 3, 4, 4, 5, 12, 13, 14, 15, 16, 17, 17, 20))

returns:

min  max
2    5
12   17
20   20

Although any output format would be fine. My current brute-force, for-loop method is pretty slow.

(Apologies if I could have easily re-interpreted the Python answer and I'm being stupid!)


回答1:


Just use diff:

x = c(2, 3, 4, 4, 5, 12, 13, 14, 15, 16, 17, 17, 20)

start = c(1, which(diff(x) != 1 & diff(x) != 0) + 1)
end = c(start - 1, length(x))

x[start]
# 2 12 20
x[end]
# 5 17 20


来源:https://stackoverflow.com/questions/16324897/finding-groups-of-contiguous-numbers-in-a-list

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