[英]purrr - How to use map2 if one input is a list of lists?
Consider first a basic case of map2
usage like this:首先考虑像这样使用
map2
的基本情况:
listA <- list(1, 2, 3)
listB <- list(4, 5, 6)
map2(listA, listB, sum)
However, what if we have a situation where one input is a list of lists, and the other input is just a list:但是,如果我们遇到这样一种情况,其中一个输入是列表的列表,而另一个输入只是一个列表:
listA <- list(list(1, 2, 3),
list(4, 5, 6))
listB <- list(7, 8, 9)
How can I achieve this desired output with purrr
?:如何使用 purrr 实现所需的
purrr
list(list(8, 10, 12),
list(11, 13, 15))
You can use map
twice.您可以使用
map
两次。
library(purrr)
map(listA, map2, listB, sum)
# this version might show it a bit more clearly
map(listA, ~ map2(.x, listB, sum))
[[1]]
[[1]][[1]]
[1] 8
[[1]][[2]]
[1] 10
[[1]][[3]]
[1] 12
[[2]]
[[2]][[1]]
[1] 11
[[2]][[2]]
[1] 13
[[2]][[3]]
[1] 15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.