Home > Blockchain >  How to turn a vector into a list with known nest structure in R?
How to turn a vector into a list with known nest structure in R?

Time:09-07

I want to turn a x dimensional vector into a nested list that has x elements. The nested list should have the same nest structure as a known list. Is there a simple way to do this?

For example, the vector to be transformed is

vector <- rnorm(10)

while the list with known structure is

list <- list( list(rnorm(2),rnorm(2)),
              list(rnorm(3),rnorm(3)) )
[[1]]
[[1]][[1]]
[1] -1.113833  1.158779

[[1]][[2]]
[1]  0.09773685 -1.62518666


[[2]]
[[2]][[1]]
[1] -1.134478 -1.091703 -0.109145

[[2]][[2]]
[1] -0.5181986 -1.9268952 -0.8527101

Another similar situation is that I may know the length of each sublist

length_list <- list( list(2,2), list(3,3) )

CodePudding user response:

You can use relist.

x <- 1:10
lst <- list( list(rnorm(2),rnorm(2)),
              list(rnorm(3),rnorm(3)) )

relist(x, lst)
#[[1]]
#[[1]][[1]]
#[1] 1 2
#
#[[1]][[2]]
#[1] 3 4
#
#
#[[2]]
#[[2]][[1]]
#[1] 5 6 7
#
#[[2]][[2]]
#[1]  8  9 10

Or for the other case create a list with rapply.

x <- 1:10
length_list <- list( list(2,2), list(3,3) )

relist(x, rapply(length_list, rep, x=0, how="list"))
#[[1]]
#[[1]][[1]]
#[1] 1 2
#
#[[1]][[2]]
#[1] 3 4
#
#
#[[2]]
#[[2]][[1]]
#[1] 5 6 7
#
#[[2]][[2]]
#[1]  8  9 10
  • Related