purrr map equivalent of nested for loop

后端 未结 4 424
借酒劲吻你
借酒劲吻你 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:40

    Just Running through this now.

    walk(1:4,~ walk(1:6, ~ print(paste(.x, .y, sep = "-")),.y=.x)) 
    [1] "1-1"
    [1] "2-1"
    [1] "3-1"
    [1] "4-1"
    [1] "5-1"
    [1] "6-1"
    [1] "1-2"
    

    and

    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] "1-2"
    

    but to match your nested for loops exactly it fiddled and this works.

    for (i in 1:4) {
      for (j in 1:6) {
        print(paste(i, j, sep = "-"))
      }
    }
    [1] "1-1"
    [1] "1-2"
    [1] "1-3"
    [1] "1-4"
    [1] "1-5"
    [1] "1-6"
    [1] "2-1"
    
    purrr::pwalk(expand.grid(1:6,1:4),~print(paste(.y, .x, sep = "-")))
    [1] "1-1"
    [1] "1-2"
    [1] "1-3"
    [1] "1-4"
    [1] "1-5"
    [1] "1-6"
    [1] "2-1"
    
    #or even a map of this
    walk(1:4,~ walk(1:6, ~ print(paste(.y, .x, sep = "-")),.y=.x))
    

    I have yet to figure out why the .y=.x is at the end though.

提交回复
热议问题