Split a Vector by Its Sequences

Split a vector by its sequences

split(x, cumsum(c(TRUE, diff(x)!=1)))
#$`1`
#[1] 7
#
#$`2`
#[1] 1 2 3 4
#
#$`3`
#[1] 6 7
#
#$`4`
#[1] 9

Split vector into group by sequence

You can use floor() function to round down and use that as your splitting rule, i.e.

split(a, floor(a))

which gives,

$`0`
[1] 0.2

$`1`
[1] 1.4 1.8

$`4`
[1] 4.2

$`6`
[1] 6.7 6.8

$`7`
[1] 7.4

R: Split a Vector into Some Overlapping Sub-vectors with Its First Element being Rebounded

Fill a matrix with appropriate dimensions, index, and split

asplit(
matrix(ts, nrow = length(ts) + 1, ncol = length(ts) - l + 1)[1:(l + 1), ],
MARGIN = 2)

#[[1]]
#[1] 1 2 3 4 5 6 7
#
#[[2]]
#[1] 2 3 4 5 6 7 8
#
#[[3]]
#[1] 3 4 5 6 7 8 9
#
#[[4]]
#[1] 4 5 6 7 8 9 10
#
#[[5]]
#[1] 5 6 7 8 9 10 11
#
#[[6]]
#[1] 6 7 8 9 10 11 1

How to split a vector into a particular list?

x = c(102, 104, 89, 89, 76)

splitter <- function(v) {
n <- length(x)
z <- NULL
z[[1]] <- NA
for(i in 2:n-1) {
z[[i+1]] <- x[1:i]
}
z
}

splitter(x)

Splitting a vector by a pattern

Try to pre-allocate the memory that you are going to use to avoid copies. Assuming a contains full sequences, you can do:

b.reserve(a.size() / 2);
c.reserve(a.size() / 2);
for (auto it = a.begin(); it < a.end(); it += 8) {
b.insert(b.end(), it, it + 4);
c.insert(c.end(), it + 4, it + 8);
}

Update

If you don't mind modifying the original vector a, you can use it to keep one of the subsequences and avoid allocating more memory. Assuming a contains full sequences:

b.reserve(a.size() / 2);
auto writer = a.begin();
for (auto reader = a.cbegin(); reader < a.cend(); reader += 8, writer += 4) {
b.insert(b.end(), reader, reader + 4);
std::copy(reader + 4, reader + 8, writer);
}
a.resize(a.size() / 2);

Split vector into several vectors depending on its content

Something simpler:

target=[100 100 100 100 200 200 400 400 400];

A = target(target==100)
B = target(target==200)
C = target(target==400)

How this works: target==x returns a logical array of size equal to target. Then you can use that logical array to index target.



Related Topics



Leave a reply



Submit