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.
expand.grid(list.1, list.b)
gives you the desired result in a data.frame
structure. 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)
This gets you what you are looking for:
unlist(lapply(list.a, function(X) {
lapply(list.b, function(Y) {
c(X, Y)
})
}), recursive=FALSE)
Here is a function you can pass lists to to expand
expand.list <- function(...){
lapply(as.data.frame(t((expand.grid(...)))),c, recursive = TRUE, use.names = FALSE)}
expand.list(list.a, list.b)
Surprised nobody has mentioned this simple one liner:
as.list(outer(list.a,list.b, paste))
[[1]]
[1] "a d"
[[2]]
[1] "b d"
[[3]]
[1] "c d"
[[4]]
[1] "a e"
Here is a somewhat brute force approach that will, given they are the same dimensions, append 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
来源:https://stackoverflow.com/questions/13018173/elementwise-combination-of-two-lists-in-r