简体   繁体   中英

How to splitting a list of vectors to small lists in decreasing order in r

Suppose I have a function which returns me a list of several vectors. Assume that I would like to split this list to small lists of different numbers of vectors. The number of the vectors in each list is different from one list to another. I need to create these lists in a decreasing order.

Genearal example:

Suppose I have n variables. Then, k = n:2 . My function will return me a list of n(n-1)/2 vectors. Then, the number of the new sub-lists is n - 1 . Hence, I need to have n-1 different lists. The number of the vectors in each list is J = 1:k-1 .

Numerical example:

If n=4 , then, k=4, 3, 2 , then, J=3,2,1 . Hence, my function will return me 6 vectors. These vectors should be stored into different lists. The number of the vectors in each list is based on J . Hence, I will have 3 different lists as follows:

  • 3 vectors in the first list.
  • 2 vectors in the second list.
  • one vector in the last list.

In other words, the returned list (the output of my function) should be split into sub-lists in a decreasing order based on J .

My function is very complicated. Hence, I will provide a list of 6 vectors as the output of my function.

Suppose my function return me the following list:

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

How I can split it into sub-lists as described above? The excepted output is:

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

I tried this:

x_sub <- list()
for(j in 1:(k-1)){
    x_sub[[j]] <- x[[i]]
    }

and of course, it is not what I expected.

Any idea, please? How I generate it for an arbitrary number of vectors? for example, how I can apply the split idea over n vectors?

Many thanks for all helps.

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

You can try the function split() to partition your list x by certain format. I don't understand what you mean for n , k , J , so you need to define them by yourself. I just simply set J as 1:3 .

J <- 1:3
breaks <- rep(J, rev(J)) # [1] 1 1 1 2 2 3
y <- split(x, f = breaks)
names(y) <- paste0("x_sub", J)
list2env(y, envir = .GlobalEnv)

x_sub1
x_sub2
x_sub3

We can use rep to split the list into a list of lists

lst <- split(x, rep(paste0("x_sub", 1:3), 3:1))

and extract the nested list with the name

lst[["x_sub1"]]

It is better not to create multiple objects in the global environment. But, if it is needed, then use list2env

list2env(lst, envir = .GlobalEnv)
x_sub1
#$x1
#[1] 1 2 3

#$x2
#[1] 1 4 3

#$x3
#[1] 3 4 6

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.

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