1

我正在尝试使用 purrr::map 从当前工作 R 空间中的列表中编写 excel 文件。我想使用每个列表的名称作为 excel 文件名(例如:name_1.xlsx、name_2.xlsx)。我怎样才能得到 purrr:map 来做呢?

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

我已经尝试过这两种解决方案,但它们不能正常工作。

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

map(l2, ~write_xlsx(l2, path = str_c(names(l2), ".xlsx")))
4

1 回答 1

1

我认为您需要map2同时提供l2&names(l2)write_xlsx. 这里.xl2.ynames(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"

编辑:您也可以使用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")))
于 2018-05-10T22:53:42.990 回答