Home > Mobile >  Convert multiple list to nested list of given structure using function [R]
Convert multiple list to nested list of given structure using function [R]

Time:06-23

I have a set of lists which I would like to convert into the nested list of a certain structure. My initial data look like list_1_1 ... list_2_2. I would like them to be like final_desired_output.

I can do this step by step by extracting desired variable and appending to the output list one by one. However, this dummy example contains only 2 data subsets (first_lists and list second_lists), while the real life data are far >1 GB. Thus, I would like to do it with a function, which I unfortunatly do not know how to do, as nested lists are not well covered in tutorials. Any assistance?

# some dummy data

one_1 <- c(1:10)
one_2 <- c(2:15)
one_3 <- c(3:20)

starting_one_1 <- 1
starting_one_2 <- 2
starting_one_3 <- 3

ending_one_1 <- c(11)
ending_one_2 <- c(16)
ending_one_3 <- c(21)


two_1 <- c(1:100)
two_2 <- c(1:15)


starting_two_1 <- 5
starting_two_2 <- 10

ending_two_1 <- c(101)
ending_two_2 <- c(16)

# lists mimicking output I currently have

list_1_1 <- list(one_1, one_2, one_3)
list_1_2 <- list(starting_one_1, starting_one_2, starting_one_3)
list_1_3 <- list(ending_one_1, ending_one_2, ending_one_3)

list_2_1 <- list(two_1, two_2)
list_2_2 <- list(starting_two_1, starting_two_2)
list_2_3 <- list(ending_two_1, ending_two_2)

# producing desired otput

list_1_1_desired <- list()

list_1_1_desired[["sequence"]] <- one_1
list_1_1_desired[["starting"]] <- starting_one_1
list_1_1_desired[["ending"]] <- ending_one_1


list_1_2_desired <- list()

list_1_2_desired[["sequence"]] <- one_2
list_1_2_desired[["starting"]] <- starting_one_2
list_1_2_desired[["ending"]] <- ending_one_2

list_1_3_desired <- list()

list_1_3_desired[["sequence"]] <- one_3
list_1_3_desired[["starting"]] <- starting_one_3
list_1_3_desired[["ending"]] <- ending_one_3

list_2_1_desired <- list()

list_2_1_desired[["sequence"]] <- two_1
list_2_1_desired[["starting"]] <- starting_two_1
list_2_1_desired[["ending"]] <- ending_two_1

list_2_2_desired <- list()

list_2_2_desired[["sequence"]] <- two_2
list_2_2_desired[["starting"]] <- starting_two_2
list_2_2_desired[["ending"]] <- ending_two_2



first_lists <- list(list_1_1_desired, list_1_2_desired, list_1_3_desired)
names(first_lists) <- c("one_1", "one_2", "one_3")

second_lists <- list(list_2_1_desired, list_2_2_desired)
names(second_lists) <- c("two_1", "two_2")

# this is what I would like to obtain
final_desired_output <- list()

final_desired_output[["one"]] <- first_lists
final_desired_output[["two"]] <- second_lists

CodePudding user response:

You could use purrr::transpose:

out <- mget(ls(pattern = '^list.*\\d$')) %>%
  split(sub("_\\d $", '', names(.))) %>%
  map(~transpose(set_names(.,c('sequence', 'starting', 'ending'))))

all.equal(out, final_desired_output, check.attributes = FALSE)
[1] TRUE
  • Related