繁体   English   中英

使用purrr函数并行迭代两个嵌套列表

[英]Iterate over two nested lists in parallel using purrr functions

我正在玩一些purrr函数,发现(令我高兴) purrr::at_depth(.x, .depth, .f, ...)purrr::map(x, . %>% map(fun))缩写purrr::at_depth(.x, .depth, .f, ...) purrr::map(x, . %>% map(fun))

问题: 当我有两个要并行迭代的嵌套列表时,是否有类似的功能或执行相同操作的正确“ purrr ”?

举个例子:

x <- list(list(10, 20), list(30, 40))
y <- list(list(1, 2), list(3, 4))

a <- list()
for(i in seq_along(x)) {
   a[[i]] <- map2(x[[i]], y[[i]], `+`) 
}

这可以工作,但是它很脏,我想避免for循环。

您具有列表列表,并且+没有针对列表进行矢量化,可以使用map2两次,第一个map2同时循环遍历x,y,第二个map2以元素明智的方式添加子列表:

map2(x, y, map2, `+`)

#[[1]]
#[[1]][[1]]
#[1] 11

#[[1]][[2]]
#[1] 22


#[[2]]
#[[2]][[1]]
#[1] 33

#[[2]][[2]]
#[1] 44

暂无
暂无

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

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