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