Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elementwise combination of two lists in R

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 combine these lists recursively, such that the result would be a list of combined elements as a vector like the following:

[[1]]
[1] a d

[[2]]
[1] a e

[[3]]
[1] a f

[[4]]
[1] b d

and so on. I feel like I'm missing something relatively simple here. Any help?

Cheers.

like image 792
sinclairjesse Avatar asked Oct 22 '12 19:10

sinclairjesse


People also ask

How do I combine multiple lists into one in R?

Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do. call functions. When combining the lists this way, the second list elements will be appended at the end of the first list.

How do I extract an element from a list in R?

The [[ operator can be used to extract single elements from a list. Here we extract the first element of the list. The [[ operator can also use named indices so that you don't have to remember the exact ordering of every element of the list. You can also use the $ operator to extract elements by name.

How do you generate all possible combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

How do you add a list in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.


2 Answers

expand.grid(list.a, list.b) gives you the desired result in a data.frame. This tends to be the most useful format for working with data in R. However, you could get the exact structure you ask for (save the ordering) 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 ordered by the first element:

result.list <- result.list[order(sapply(result.list, head, 1))]
like image 193
Matthew Plourde Avatar answered Oct 01 '22 09:10

Matthew Plourde


You want mapply (if by "recursively" you mean "in parallel"):

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

Or maybe this is more what you want:

unlist(lapply(list.a, function(a) lapply(list.b, function (b) c(a, b))), recursive=FALSE)
like image 40
dholstius Avatar answered Oct 01 '22 11:10

dholstius