a<-list(1,2,3,c(4,5),6,7) > a [[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3 [[4]] [1] 4 5 [[...">

Combine specific objects into a list

"a" is a list.

> a<-list(1,2,3,c(4,5),6,7)
> a
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4 5

[[5]]
[1] 6

[[6]]
[1] 7

"b" is a conversion indicator.

b<-c(3,2,1)

I want to group (or combine) objects in "a" according to the number in "b", this means that the first 3 groups of objects are together, and then the next two, finally, the last, expected result is as follows:

[[1]]
[1] 1 2 3

[[2]]
[1] 4 5 6

[[3]]
[1] 7

I can use "cumsum" to summarize the three groups, but I don’t know how to display each object as described above. Thank.

+4
source share
3 answers

Another variant:

lapply(split(a, cumsum(sequence(b)==1)), unlist)
#$`1`
#[1] 1 2 3

#$`2`
#[1] 4 5 6

#$`3`
#[1] 7
+2
source
tapply(a, rep(seq_along(b), b), Reduce, f = `c`)
$`1`
[1] 1 2 3

$`2`
[1] 4 5 6

$`3`
[1] 7
+4
source

Another attempt:

grps <- rep(rep(seq_along(b), b), lengths(a))
relist(unlist(a), split(grps,grps) )

#$`1`
#[1] 1 2 3
#
#$`2`
#[1] 4 5 6
#
#$`3`
#[1] 7
+1
source

All Articles