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")))
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!!
Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.
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'.
There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With