Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split vector at unknown index

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).

Example,

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;
}

I'm looking forward for your help!

like image 265
Michiel uit het Broek Avatar asked Jul 04 '13 01:07

Michiel uit het Broek


People also ask

How do I split a vector in R?

Use the split() function in R to split a vector or data frame. Use the unsplit() method to retrieve the split vector or data frame.


1 Answers

Try this,

split(data, cumsum(c(0, diff(data)>=2)))
like image 124
baptiste Avatar answered Oct 07 '22 05:10

baptiste