本文介绍了在未知索引处分割向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个向量,该向量至少包含50.000个实数.值从小到大排序,现在我需要将此向量拆分为不同的向量.当两个数字之间的差大于给定数字(例如两个)时,必须对向量进行拆分.

I have a vector in R which contains at least 50.000 reals.The values are ordered from small to large and now I need to split up this vector in different vectors. The vector has to be split up when the difference between two numbers is larger than a given number (say two).

示例

data <- c(1,1.1, 1.2, 4, 4.2, 8, 8.9, 9, 9.3);
# Then I need the following vectors:
x1 <- c(1, 1.1, 1.2);
x2 <- c(4, 4.2);
x3 <- c(8, 8.9, 9, 9.3);

困难在于我们不知道所需矢量的数量,也不知道正手每个矢量的长度.

The difficulty is that we don't know the number of needed vectors and don't know the length of each vector at forehand.

现在我有以下想法,但是这非常耗时,并且只能将向量分成两个新向量.

Now I have the following idea, however this is very time consuming and it is only able to split the vector into two new vectors.

j <- 2;
seqDemA1 <- seqDemandA[1];
while((seqDemandA[j-1] - seqDemandA[j] < 2) && (j < length(seqDemandA)+1)) {
    seqDemA1 <- c(seqDemA1, seqDemandA[j]);
    j <- j+1;
}
seqDemA2 <- seqDemandA[j];
j <- j+1;
while((seqDemandA[j-1] - seqDemandA[j] < 2) && (j < length(seqDemandA)+1)) {
    seqDemA2 <- c(seqDemA2, seqDemandA[j]);
    j <- j+1;
}

期待您的帮助!

推荐答案

尝试一下,

split(data, cumsum(c(0, diff(data)>=2)))

这篇关于在未知索引处分割向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:53