Suppose I have a list of vectors x
as follows:
> 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 <- c(3,3)
y1 <- c(2,4)
I would like to split x
based on the values of y
and y1
. 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)
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.
I tried this:
> z <- split(x, y[1]))
but it is not what I expected.
The output should be as follows:
based on y
:
sublist_1 = list(x1, x2, x3),
sublist_2= list(x4,x5,x6)
based on 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(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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.