purrr 映射等效于嵌套 for 循环 [英] purrr map equivalent of nested for loop

查看:46
本文介绍了purrr 映射等效于嵌套 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

purrr::map 相当于:

What is the purrr::map equivalent of:

for (i in 1:4) {
  for (j in 1:6) {
    print(paste(i, j, sep = "-"))
  }
}

lapply(1:4, function(i) 
  lapply(1:6, function(j) 
    print(paste(i, j, sep = "-"))))

从概念上讲,我不明白的是如何在 inner 映射函数中引用 outer 循环.

Conceptually, what I'm not getting is how to refer to the outer loop in the inner map function.

map(1:4, ~ map(1:6, ~ print(paste(.x, ????, sep = "-")))

推荐答案

正如@r2evans 指出的那样,第一个调用中的 .x 被屏蔽了.但是,您可以创建一个带有 2 个参数 .x.y 的 lambda 函数,并将之前的 .x 分配给新的 .y 通过 ... 参数.

As @r2evans points out, the .x from your first call is masked. however you can create a lambda function that takes 2 parameters .x and .y, and assign the previous .x to the new .y through the ... argument.

我将使用 walk 而不是 map 因为在这种情况下你只对副作用(打印)感兴趣

I'll use walk rather than map as in this case you're only interested in side effects (printing)

walk(1:4,~ walk(1:6, ~ print(paste(.x, .y, sep = "-")),.y=.x))

另一种选择是使用 expand.grid 来布置组合,然后使用 pwalk(或其他中的 pmap情况)

Another option is to use expand.grid to lay out the combinations, and then iterate on those with pwalk (or pmap in other circumstances)

purrr::pwalk(expand.grid(1:4,1:6),~print(paste(.x, .y, sep = "-")))

两种情况下的输出:

[1] "1-1"
[1] "2-1"
[1] "3-1"
[1] "4-1"
[1] "5-1"
[1] "6-1"
[1] "1-2"
[1] "2-2"
[1] "3-2"
[1] "4-2"
[1] "5-2"
[1] "6-2"
[1] "1-3"
[1] "2-3"
[1] "3-3"
[1] "4-3"
[1] "5-3"
[1] "6-3"
[1] "1-4"
[1] "2-4"
[1] "3-4"
[1] "4-4"
[1] "5-4"
[1] "6-4"

这篇关于purrr 映射等效于嵌套 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆