如何在R中并行合并两个列表?

时间:2016-12-16 22:12:31

标签: r merge

我想知道如何并行合并两个列表,而不是按顺序附加如下代码。

例如,

A <- list(c(1,2,3), c(3,4,5), c(6,7,8))

B <- list(c("a", "b", "c"), c("d", "e", "f"), c("g", "h", "i"))

结果,

[[1]]
[[1]][[1]]
[1] 1 2 3

[[1]][[2]]
[1] "a" "b" "c"


[[2]]
[[2]][[1]]
[1] 3 4 5

[[2]][[2]]
[1] "d" "e" "f"


[[3]]
[[3]][[1]]
[1] 6 7 8

[[3]][[2]]
[1] "g" "h" "i"

2 个答案:

答案 0 :(得分:6)

简单地使用Map

   Map(list,A,B)

答案 1 :(得分:0)

更长的方法(不是递归的,直到第二级合并):

A <- list(c(1,2,3), c(3,4,5), c(6,7,8))

B <- list(c("a", "b", "c"), c("d", "e", "f"), c("g", "h", "i"))

mergepar <- function(x = A, y = B) { # merge two lists in parallel
    ln <- max(length(x), length(y)) # max length
    newlist <- as.list(rep(NA, ln)) # empty list of max length

    for (i in 1:ln) { # for1, across length
        # two level subsetting (first with [ and then [[, so no subscript out of bound error) and lapply
        newlist[[i]] <- lapply(list(A, B), function(x) "[["("["(x, i), 1)) 
    }

    return(newlist)
}