elementwise combination of two lists in R

天大地大妈咪最大 提交于 2019-12-05 00:42:33

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!