"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.
tapply(a, rep(seq_along(b), b), Reduce, f = `c`)
$`1`
[1] 1 2 3
$`2`
[1] 4 5 6
$`3`
[1] 7
Another option is
lapply(split(a, cumsum(sequence(b)==1)), unlist)
#$`1`
#[1] 1 2 3
#$`2`
#[1] 4 5 6
#$`3`
#[1] 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With