elementwise combination of two lists in R

sinclairjesse picture sinclairjesse · Oct 22, 2012 · Viewed 14.1k times · Source

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.

Answer

Matthew Plourde picture Matthew Plourde · Oct 22, 2012

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))]