Home > Back-end >  Use map() function to read and merge another files list
Use map() function to read and merge another files list

Time:11-17

I have three files list

filesl <- list.files(pattern = 'RP-L-.*\\.xls', full.names = TRUE)
filesr <- list.files(pattern = 'RP-R-.*\\.xls', full.names = TRUE)
filesv <- list.files(pattern = 'RP-V-.*\\.xls', full.names = TRUE)

And I've attemped to read and merge two of them as follows:

data <- map2_dfr(filesl, filesr, ~ {
  ldat <- readxl::read_excel(.x)
  rdat <- readxl::read_excel(.y)
  df <- rbind.data.frame(ldat, rdat, by = c('ID', 'GR', 'SES', 'COND'))
})

If I would like to add the third one list filesv what am I supposed to set as function? I guess I should use one from package purrr enabling function iteration on multiple elements (such pmap, imap and so on, but I am not able to change the commands properly).

Any suggestions as regards

Thanks in advance

CodePudding user response:

data <- pmap_dfr(list(filesl, filesr, filesv), ~ {
  ldat <- readxl::read_excel(..1)
  rdat <- readxl::read_excel(..2)
  vdat <- readxl::read_excel(..3)
  df <- rbind.data.frame(ldat, rdat, vdat, by = c('ID', 'GR', 'SES', 'COND'))
})

pmap takes a list of lists to iterate on. Then the arguments can be referred to as ..1, ..2, etc in the anonymous function.

  • Related