I want R script to split a parent vector (1 to n) to overlapping sub-vectors with equal and constant length. In that case, the last sub-vector who does not have its length equal to the set length as a result of the parent vector be exhausted need to return to the beginning of the parent vector to use as many as it may need to make up its set constant length. Then the split will stop.
I have an R code that gives the starts and ends of each block as below:
blocks <- function(len, ov, n) {
starts <- unique(sort(c(seq(1, n, len), seq(len-ov+1, n, len))))
ends <- pmin(starts + len - 1, n)
# truncate starts and ends to the first num elements
num <- match(n, ends)
head(data.frame(starts, ends), num)
}
vec = 1:17
len = 8
ov = ceiling(len/2)
b <- blocks(len, ov, length(vec))
b
b provides a data frame that shows how I want each sub-vector to be divided (the start and end) of each sub-vector except the end of the last vector who may not length up to the rest. The r code below print the split
with(b, Map(function(i, j) vec[i:j], starts, ends))
#[[1]]
#[1] 1 2 3 4 5 6 7 8
#[[2]]
#[1] 5 6 7 8 9 10 11 12
#[[3]]
#[1] 9 10 11 12 13 14 15 16
#[[4]]
#[1] 13 14 15 16 17
What I want
I want how to get r to let the last sub-vector to use as many first element(s) of the parent vector to make up its set length, and if the last sub-vector is length sufficient, no further action is needed.
#[[1]]
#[1] 1 2 3 4 5 6 7 8
#[[2]]
#[1] 5 6 7 8 9 10 11 12
#[[3]]
#[1] 9 10 11 12 13 14 15 16
#[[4]]
#[1] 13 14 15 16 17 1 2 3