我有一系列的值
c(1,2,3,4,5,8,9,10,13,14,15)我想找出数字变得不连续的范围。我只想要这个作为输出:
(1,5)
(8,10)
(13,15)我需要找到突破点。
我需要在R中完成它。
发布于 2014-04-16 06:14:36
像这样的东西?
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另一个例子:
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发布于 2014-04-16 06:27:41
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)发布于 2014-04-16 08:21:05
我发布了seqle,它将在一行代码中为您完成此任务。您可以加载cgwtools包或搜索代码,因为它已经发布了几次。
https://stackoverflow.com/questions/23095415
复制相似问题