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!
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.
Try this,
split(data, cumsum(c(0, diff(data)>=2)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With