Reputation: 788
"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 transform indicator.
b<-c(3,2,1)
I want group(or combine) objects in "a" according to the number in "b", that means the first 3 objects group together, then the next two, finally the last, the expected result is as follows:
[[1]]
[1] 1 2 3
[[2]]
[1] 4 5 6
[[3]]
[1] 7
I can only use "cumsum" to sum the three groups, but don't know how to display each object as listed above. Thanks.
Upvotes: 4
Views: 74
Reputation: 93813
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
Upvotes: 1
Reputation: 886948
Another option is
lapply(split(a, cumsum(sequence(b)==1)), unlist)
#$`1`
#[1] 1 2 3
#$`2`
#[1] 4 5 6
#$`3`
#[1] 7
Upvotes: 2
Reputation: 48191
tapply(a, rep(seq_along(b), b), Reduce, f = `c`)
$`1`
[1] 1 2 3
$`2`
[1] 4 5 6
$`3`
[1] 7
Upvotes: 4