Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine specific objects in a list

Tags:

list

r

"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.

like image 441
lightsnail Avatar asked Mar 13 '23 09:03

lightsnail


2 Answers

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

$`2`
[1] 4 5 6

$`3`
[1] 7
like image 196
Julius Vainora Avatar answered Mar 20 '23 16:03

Julius Vainora


Another option is

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

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

#$`3`
#[1] 7
like image 25
akrun Avatar answered Mar 20 '23 17:03

akrun