0

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

Max
  • 10,701
  • 2
  • 24
  • 48
12666727b9
  • 1,133
  • 1
  • 8
  • 22

1 Answers1

2
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.

Aurèle
  • 12,545
  • 1
  • 31
  • 49
  • 1
    thank you so much. I though that argurments should have indexed as `.x, .y, .z` – 12666727b9 Nov 16 '21 at 15:14
  • See e.g. `?map2_dfr` for the relevant documentation, that also includes that of `pmap_dfr` and anonymous function syntax hints – Aurèle Nov 16 '21 at 15:15
  • Btw I'm getting back an error with `rbind.data.frame()`. With those three dataset: `the nu,ber of arguments columns does not correspond ` – 12666727b9 Nov 16 '21 at 15:20
  • Could be that `rbind` does not take a `by` argument, but it is hard to say without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Aurèle Nov 16 '21 at 15:24
  • Then it's likely that the Excel tables have different number of columns. Consider using `dplyr::bind_rows` as a replacement for `rbind` – Aurèle Nov 16 '21 at 15:25
  • It worked. Thanks – 12666727b9 Nov 16 '21 at 15:37