Elemental combination of two lists in R

Let's say I have two lists:

list.a <- as.list(c("a", "b", "c")) list.b <- as.list(c("d", "e", "f")) 

I would like to merge these lists recursively, so the result will be a list of merged items as a vector like the following:

 [[1]] [1] ad [[2]] [1] ae [[3]] [1] af [[4]] [1] bd 

etc. I feel like I'm missing something relatively simple here. Any help?

Greetings.

+4
source share
5 answers

expand.grid(list.1, list.b) gives the desired result in the data.frame structure. This is usually the most useful format for working with data in R. However, you can get the exact structure that you request (save the order) with a call to apply and lapply :

 result.df <- expand.grid(list.a, list.b) result.list <- lapply(apply(result.df, 1, identity), unlist) 

If you want this list to be ordered by the first element:

 result.list <- result.list[order(sapply(result.list, head, 1))] 
+11
source

You want mapply (if "recursively" means "in parallel"):

 mapply(c, list.a, list.b, SIMPLIFY=FALSE) 

Or maybe this is more than what you want:

 unlist(lapply(list.a, function(a) lapply(list.b, function (b) c(a, b))), recursive=FALSE) 
+5
source

This gives you what you are looking for:

 unlist(lapply(list.a, function(X) { lapply(list.b, function(Y) { c(X, Y) }) }), recursive=FALSE) 
+3
source

Here is a function with which you can pass lists to expand

 expand.list <- function(...){ lapply(as.data.frame(t((expand.grid(...)))),c, recursive = TRUE, use.names = FALSE)} expand.list(list.a, list.b) 
+2
source

Here is a few brute force approaches, which, provided they are the same size, adds list.b to list.a recursively using the append function.

 # CREATE LIST OBJECTS list.a <- as.list(c("a", "b", "c")) list.b <- as.list(c("d", "e", "f")) # CREATE AN EMPTY LIST TO POPULATE list.ab <- list() # DOUBLE LOOP TO CREATE RECURSIVE COMBINATIONS USING append ct=0 for( i in 1:length(list.a) ) { for (j in 1:length(list.b) ) { ct=ct+1 list.ab[[ct]] <- append(list.a[[i]], list.b[[j]]) } } # PRINT RESULTS list.ab 
+1
source

Source: https://habr.com/ru/post/1441366/


All Articles