Reputation: 1480
I have a list of 7 vectors, I would like to group the lists into 4 lists of vectors each.
B2 <- list ( c (12 , 47 ,137 ,170), c(44 , 47 ,135, 170) , c(12 , 28 , 34 , 44 , 47 , 59 , 61 , 67 , 76 , 80 , 84 ,135, 148, 170) , c(44 , 47 , 84 ,135 ,170) , c(12 , 28 , 34 , 44 , 47 , 59 , 61 , 67 , 76 , 80 , 84 ,135, 148, 156, 159, 164, 170) , c(12 , 28 , 34 , 44 , 47 , 84 ,135 ,170) , c(12 , 28 , 44 , 47 , 84, 135, 170))
# I would like to create four groups (lists) as per the following index of consecutive list sequence)
Subgroup <- c(2,4,5,7)
# Desired Output
B2 <- list ( list ( c (12 , 47 ,137 ,170), c(44 , 47 ,135, 170)) , list ( c(12 , 28 , 34 , 44 , 47 , 59 , 61 , 67 , 76 , 80 , 84 ,135, 148, 170) , c(44 , 47 , 84 ,135 ,170)) , list ( c(12 , 28 , 34 , 44 , 47 , 59 , 61 , 67 , 76 , 80 , 84 ,135, 148, 156, 159, 164, 170)) , list ( c (12 , 28 , 34 , 44 , 47 , 84 ,135 ,170) , c(12 , 28 , 44 , 47 , 84, 135, 170)))
Upvotes: 3
Views: 88
Reputation: 11597
Using split
and rep
:
split(B2, rep(1:length(Subgroup), diff(c(0, Subgroup))))
Upvotes: 1
Reputation: 887078
Here is an option using sequence
i1 <- sequence(Subgroup)
i2 <- !duplicated(i1)
res <- split(B2[i1[i2]],cumsum(c(TRUE,diff(i1)<0))[i2])
all.equal(res, Out, check.attributes=FALSE)
#[1] TRUE
Or as @Chris mentioned in the comments,
lst <- Map(`:`, c(1,head(Subgroup,-1)+1), Subgroup)
lapply(lst, function(i) B2[i])
Upvotes: 1
Reputation: 779
Another option
rng = data.frame(1+c(0, head(Subgroup,-1)), Subgroup)
apply(rng, 1,function(x) B2[x[1]:x[2]])
Upvotes: 1