这个问题在这里已经有了答案:
Create grouping variable for consecutive sequences and split vector
(5 个回答)
2年前关闭。
如果我有一个这样的向量:
dat <- c(1,2,3,4,5,19,20,21,56,80,81,92)
我怎样才能把它分解成一个列表:
[[1]]
1 2 3 4 5
[[2]]
19 20 21
[[3]]
56
[[4]]
80 81
[[5]]
92
最佳答案
只需使用 split
结合 diff
:
> split(dat, cumsum(c(1, diff(dat) != 1)))
$`1`
[1] 1 2 3 4 5
$`2`
[1] 19 20 21
$`3`
[1] 56
$`4`
[1] 80 81
$`5`
[1] 92
不完全是你所要求的,但“R.utils”包有几个相关的有趣功能:
library(R.utils)
seqToIntervals(dat)
# from to
# [1,] 1 5
# [2,] 19 21
# [3,] 56 56
# [4,] 80 81
# [5,] 92 92
seqToHumanReadable(dat)
# [1] "1-5, 19-21, 56, 80-81, 92"
关于r - 在 R 中查找向量中的连续值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837401/