如何在向量列表中对列表进行分组

时间:2016-01-27 13:56:29

标签: r

我有一个包含7个向量的列表,我想将列表分为4个向量列表。

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))) 

3 个答案:

答案 0 :(得分:1)

以下是使用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

或者@Chris在评论中提到,

lst <- Map(`:`,  c(1,head(Subgroup,-1)+1), Subgroup)
lapply(lst, function(i) B2[i])

答案 1 :(得分:1)

另一个选择

rng = data.frame(1+c(0, head(Subgroup,-1)), Subgroup)
apply(rng, 1,function(x) B2[x[1]:x[2]])

答案 2 :(得分:1)

使用splitrep

split(B2, rep(1:length(Subgroup), diff(c(0, Subgroup))))