purrr map equivalent of nested for loop

后端 未结 4 422
借酒劲吻你
借酒劲吻你 2020-12-01 01:59

What is the purrr::map equivalent of:

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

OR

lap         


        
4条回答
  •  清歌不尽
    2020-12-01 02:43

    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.

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

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

    Output in both cases:

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

提交回复
热议问题