Jake
Jake

Reputation: 187

Convert a vector in R to a nested list

I have a vector of length n and I want to convert it to a nested list. The outer list should be of length n / 2 and each item in this list should have two sub-lists. The first sub-list in each list will hold an odd numbered element from the vector and the second sub-list will hold an even numbered element (see my example code if this isn't making sense... I'm having a hard time describing it in general terms).

Question: Is there a way to convert this vector into a nested list without using for loops? I'm doing this in the context of a simulation and so I want to make sure it is as fast as possible. The aforementioned vector will vary in length between iterations of the simulation, so I'm trying to find an answer I can generalize to a vector of length n. The vector will always be even though.

Example vector and list: ex_vector <- 1:6 ex_list <- list( list(1, 2), list(3, 4), list(5, 6) ) Edit: fixed an error in my example code

Upvotes: 1

Views: 1319

Answers (3)

akrun
akrun

Reputation: 887951

We create a grouping variable with gl and splitthe vector into a list and convert to list with as.list

n <- 2
out <- lapply(split(ex_vector, as.integer(gl(length(ex_vector), n,
                 length(ex_vector)))), as.list)
str(out)
#List of 3
# $ 1:List of 2
#  ..$ : int 1
#  ..$ : int 2
# $ 2:List of 2
#  ..$ : int 3
#  ..$ : int 4
# $ 3:List of 2
#  ..$ : int 5
#  ..$ : int 6

Or use %/% to split

lapply(split(ex_vector, (seq_along(ex_vector)-1) %/% n + 1), as.list)

Or compactly

split(as.list(ex_vector), cumsum(seq_along(ex_vector) %%2))

Upvotes: 1

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84719

I'm not sure to understand the general principle, but the code below works for the example:

> x <- apply(matrix(ex_vector, ncol=2, byrow=TRUE), 1, as.list)
> str(x)
List of 3
 $ :List of 2
  ..$ : int 1
  ..$ : int 2
 $ :List of 2
  ..$ : int 3
  ..$ : int 4
 $ :List of 2
  ..$ : int 5
  ..$ : int 6

Upvotes: 1

s_baldur
s_baldur

Reputation: 33743

n <- length(ex_vector)
lapply(split(ex_vector, rep(1:(n/2), each = 2)), split, 1:2)

Upvotes: 1

Related Questions