elementwise combination of two lists in R

丶灬走出姿态 提交于 2019-12-06 19:21:06

问题


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.


回答1:


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



回答2:


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)



回答3:


This gets you what you are looking for:

unlist(lapply(list.a, function(X) {
    lapply(list.b, function(Y) {
        c(X, Y)
    })
}), recursive=FALSE)



回答4:


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)



回答5:


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"



回答6:


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

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