在 R 中将数字向量拆分为连续的块 [英] Split a numeric vector into continuous chunks in R
本文介绍了在 R 中将数字向量拆分为连续的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个数字向量 [1 2 3 4 7 8 9 10 15 16 17],我该如何拆分它以便返回多个向量来分隔该向量的连续元素?IE.[1 2 3 4] [7 8 9 10] [15 16 17].我在 matlab 中找到了如何做到这一点的答案,但我只使用 R.
If I have a numeric vector [1 2 3 4 7 8 9 10 15 16 17], how can I split it so that I have multiple vectors returned that separate the continuous elements of that vector? I.e. [1 2 3 4] [7 8 9 10] [15 16 17]. I've found an answer of how to do this in matlab, but I only use R.
谢谢.
推荐答案
这是另一种选择:
vec <- c( 1, 2, 3, 4, 7, 8, 9, 10, 15, 16, 17 )
split(vec, cumsum(seq_along(vec) %in% (which(diff(vec)>1)+1)))
# $`0`
# [1] 1 2 3 4
#
# $`1`
# [1] 7 8 9 10
#
# $`2`
# [1] 15 16 17
这篇关于在 R 中将数字向量拆分为连续的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文