Reputation: 1433
I want to split a parent vector into subvectors of equal lengths and overlapping suvectors such that if there exists a supposed last vector who would not make the specified subvector length to be merged with its penultimate. This question is a follow-up from @rawr comment HERE
########Block function######################
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)
}
########Moving block#############
vec = 1:17
len = 8
ov = ceiling(len/2)
b <- blocks(len, ov, length(vec))
with(b, Map(function(i, j) vec[i:j], starts, ends))
1 1 2 3 4 5 6 7 8
[2] 5 6 7 8 9 10 11 12
[3] 9 10 11 12 13 14 15 16
[4] 13 14 15 16 17
What I want
I want the last list that is not up to the specified subvector to be merged to the penultimate list like this:
1 1 2 3 4 5 6 7 8
[2] 5 6 7 8 9 10 11 12
[3] 9 10 11 12 13 14 15 16 13 14 15 16 17
Upvotes: 1
Views: 49
Reputation: 887153
We can create a condition with if
out <- with(b, Map(function(i, j) vec[i:j], starts, ends))
l1 <- length(out)
if(length(out[[l1]]) < len) {
out[[l1-1]] <- unlist(out[(l1-1):l1])
out[[l1]] <- NULL
}
-output
out
[[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 13 14 15 16 17
Upvotes: 1