purrr map equivalent of nested for loop

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

    The use of function formulas (~) is a little limited when trying to nest like this, since it is perfectly unclear which level of map you are attempting to reference. (Well, that's not correct. It's perfectly clear to me that it is referencing inside-out, and since they both use the same nomenclature, the outer variables are being masked by the inner variables.)

    I think your best way around it is to not use the formula method, instead using immediate/anonymous (or predefined) functions:

    library(purrr)
    str(map(1:2, function(x) map(1:3, function(y) paste(x, y, sep = "-"))))
    # List of 2
    #  $ :List of 3
    #   ..$ : chr "1-1"
    #   ..$ : chr "1-2"
    #   ..$ : chr "1-3"
    #  $ :List of 3
    #   ..$ : chr "2-1"
    #   ..$ : chr "2-2"
    #   ..$ : chr "2-3"
    

提交回复
热议问题