简体   繁体   English

如何根据r中另一个向量的值将向量列表拆分为子列表

[英]How to split a list of vectors into sublist based on a values of another vector in r

Suppose I have a list of vectors x as follows:假设我有一个向量列表x如下:

> x <- list(x1=c(1,2,3), x2=c(1,4,3), x3=c(3,4,6), x4=c(4,8,4), x5=c(4,33,4), x6=c(9,6,7))

Suppose I have another two vectors y , y1 such that:假设我还有另外两个向量y , y1使得:

 y <- c(3,3)
 y1 <- c(2,4)

I would like to split x based on the values of y and y1 .我想根据yy1的值拆分x For example, for y , I would like to split x into two sub-lists with the same number of vectors (3 vectors in each sub-list)例如,对于y ,我想将x分成两个具有相同向量数的子列表(每个子列表中有 3 个向量)

For y1 , I would like to split x into two sub-lists with different number of vectors, where the first sub-list contains 2 vectors and the second sub-list contains 4 vectors.对于y1 ,我想将x分成两个具有不同向量数量的子列表,其中第一个子列表包含 2 个向量,第二个子列表包含 4 个向量。

I tried this:我试过这个:

> z <- split(x, y[1]))

but it is not what I expected.但这不是我所期望的。

The output should be as follows:输出应如下所示:

based on y :基于y

sublist_1 = list(x1, x2, x3), 

sublist_2= list(x4,x5,x6)

based on y1 :基于y1

sublist_1 = list(x1, x2). 
sublist_2= list(x1, x2, x3, x4).

Any help, please?请问有什么帮助吗?

We can use split to split the list into elements by creating groups to split.我们可以使用split通过创建要拆分的组来将列表拆分为元素。

split(x, rep(c(1, 2), y))

#$`1`
#$`1`$x1
#[1] 1 2 3

#$`1`$x2
#[1] 1 4 3

#$`1`$x3
#[1] 3 4 6


#$`2`
#$`2`$x4
#[1] 4 8 4

#$`2`$x5
#[1]  4 33  4

#$`2`$x6
#[1] 9 6 7

We can also write a function to do this我们也可以写一个函数来做到这一点

split_list <- function(x, split_var) {
  split(x, rep(1:length(split_var), split_var))
}

split_list(x, y1)
#$`1`
#$`1`$x1
#[1] 1 2 3

#$`1`$x2
#[1] 1 4 3


#$`2`
#$`2`$x3
#[1] 3 4 6

#$`2`$x4
#[1] 4 8 4

#$`2`$x5
#[1]  4 33  4

#$`2`$x6
#[1] 9 6 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM