简体   繁体   English

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

[英]How to merge two lists in parallel in R?

I'm asking to how to merge two lists in parallel, not orderly append as below codes. 我在问如何并行地合并两个列表,而不是按以下代码顺序附加。

For example, 例如,

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

As results, 结果,

[[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"

简单地使用Map

   Map(list,A,B)

A longer approach (not recursive yet, up to second level merging): 更长的方法(尚未递归,直到第二级合并):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM