purrr map equivalent of nested for loop

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

    Here is an addition to the already very good answers and answer-comments. I wanted to make a single purr-like function that accomplishes the OP's goals. So I made a loop_map function that behaves analogously to the main Purrr map functions.

    loop_map <- function(why, ecks, fun) {
      
      # 2: for every call of this (the previous .f) the new .f is called for each
      # value of ecks, supplied the same value of why each time
      iterate_over_x = function(x_in,y_in,fun_in){
        return(pmap(.l = list(x = x_in), .f = fun_in ,y = y_in ) %>%
     set_names(nm = as.character(x_in))) 
      }
      
      # 1: this ".f"  argument is called once for each element of why, and is 
      # supplied one value of why and every value of ecks each time
      pmap(.l = list(y_in = why), .f = iterate_over_x, x_in = ecks, fun_in = fun) %>% 
    set_names(nm = as.character(why))
      
    }
    
    
    
    my_paste <- function(x,y) {
      paste(x,y)
    }
    
    
    
    loop_map(list("a","b"),list("c","d"),my_paste)
    

    As a bonus I named the output so that one can index it more easily, or somehow convert it to a dataframe. I would like to improve this function by adding capabilities to loop over arbitrarily many input lists, and possibly to use functions that take ... arguments (right now everything has to be named). If anyone has an idea for how to do this feel free to let me know.

提交回复
热议问题