Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join 2 nested lists

Tags:

r

purrr

tidyverse

I want to combine two lists

list_1 <- list(LIST1 = list(list("a"), list("b"), list("c")))
list_2 <- list(LIST2 = list(list("1"), list("2"), list("3")))

Desired Output:

combined_list <- list()
combined_list[[1]] <- c("a", "1")
combined_list[[2]] <- c("b", "2")
combined_list[[3]] <- c("c", "3")

I have a nasty for loop way of doing this but I'd like to clean it up using purrr maybe? Any help appreciated!!

like image 402
MayaGans Avatar asked Nov 07 '19 20:11

MayaGans


People also ask

How do I merge nested lists?

Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.

How do you merge elements in a nested list in Python?

First, flatten the nested lists. Take Intersection using filter() and save it to 'lst3'. Now find elements either not in lst1 or in lst2, and save them to 'temp'. Finally, append 'temp' to 'lst3'.

How do you join two or more lists in Python?

There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator.


1 Answers

Here's a variant that recursively concatenates two nested lists of the same structure and preserves that structure

# Add additional checks if you expect the structures of .x and .y may differ
f <- function(.x, .y)
  if(is.list(.x)) purrr::map2(.x, .y, f) else c(.x, .y)

res <- f( list_1, list_2 )
# ...is identical to...
# list(LIST1 = list(list(c("a","1")), list(c("b","2")), list(c("c","3"))))

You can then unroll the structure as needed. For example, to get the desired output, you can do

purrr::flatten(purrr::flatten(res))
# [[1]]
# [1] "a" "1"
# 
# [[2]]
# [1] "b" "2"
# 
# [[3]]
# [1] "c" "3"
like image 140
Artem Sokolov Avatar answered Sep 30 '22 01:09

Artem Sokolov