[英]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.