2

I am trying to write excel files from a list in my current working R space using purrr::map. I would like to use the name of each list as the excel file name (ex: name_1.xlsx, name_2.xlsx). How do I get purrr:map to do it?

library(tidyverse)
library(writexl)

l2 <- list(
  tibble(x = 1:5, y = 1, z = x ^ 2 + y),
  tibble(x = 2:6, y = 3, z = x ^ 2 + y)
  )

names(l2) <- c("name_1", "name_2")

I have tried these two solutions but they do not work properly.

map(l2, write_xlsx, str_c(names(l2), ".xlsx"))

map(l2, ~write_xlsx(l2, path = str_c(names(l2), ".xlsx")))
  • 1
    Please be specific about what doesn't work. My guess is that you should have `.` inside your `write_xlsx` instead of `l2` – camille May 10 '18 at 22:46
  • 1
    I think using `iwalk`/`imap` (for convenience) or `walk2`/`map2` with the list and the names of the list might be what you need here. – aosmith May 10 '18 at 22:49

1 Answers1

2

I think you need map2 to supply both l2 & names(l2) to write_xlsx. Here .x refers to l2 and .y refers to names(l2)

map2(l2, names(l2), ~ write_xlsx(.x, path = str_c(.y, ".xlsx")))

$`name_1`
[1] "name_1.xlsx"

$name_2
[1] "name_2.xlsx"

Edit: you can also use walk2, pmap & pwalk

walk2(l2, names(l2), ~ write_xlsx(.x, path = str_c(.y, ".xlsx")))

# ..1 refers to l2 & ..2 refers to names(l2)
pmap(list(l2, names(l2)), ~ write_xlsx(..1, path = str_c(..2, ".xlsx")))

pwalk(list(l2, names(l2)), ~ write_xlsx(..1, path = str_c(..2, ".xlsx")))
Tung
  • 26,371
  • 7
  • 91
  • 115
  • 2
    To save some typing, you could also use `imap(l2, ~ write_xlsx(.x, path = paste0(.y, ".xlsx")))` which is a shortcut for `map2(l2, names(l2), ~ write_xlsx(.x, path = paste0(.y, ".xlsx")))` – markdly May 11 '18 at 02:50