Home > Mobile >  Pass multiple functions (each one time) ussing purrr
Pass multiple functions (each one time) ussing purrr

Time:03-21

I have a folder with different files, each with a different format, so I created different functions able to read each of the files. Is it possible to use map to apply the corresponding function to the corresponding file?

I have found this post to apply several functions to the object, but I don't think is applicable in this case since here all functions are applied always.

all_files <- list.dirs(file.path(path))
fun_A <- function(x) {read.csv(x)}
fun_B <- function(x) {read.table(x)}
fun_C <- function(x) {read.delim(x)}

funs <- c(fun_A , fun_B , fun_C)

So, if I do it manually it works:

(all_files %>% 
    purrr::map(., ~list.files(., full.names = T)))[[1]][1] %>% fun_A() %>% 
  dplyr::bind_rows((all_files %>% 
                      purrr::map(., ~list.files(., full.names = T)))[[1]][2] %>% fun_B ()) %>% 
  dplyr::bind_rows((all_files %>% 
                      purrr::map(., ~list.files(., full.names = T)))[[1]][3] %>% fun_C())

But I tried several times with purrr and I am not able to make it work. This is my final attempt:

 all_files %>%  purrr::map(.x = ., ~{
    df = (.x)
    funs %>% purrr::map(., ~ df %>% (.))
    })

Any suggestions?

CodePudding user response:

You can use Map or map2 as suggested by @akrun

do.call(rbind, Map(function(x, y) y(x), all_files, funs))

Using map2_df :

purrr::map2_df(all_files, funs, ~.y(.x))

For this to work it is expected that length(all_files) and length(funs) are equal.

  • Related