rpurrrwritexl

Write xlsx files from list in current working directory with purrr:map


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")))

Solution

  • 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")))