如何使用 purrr 将命名列表写入文件(带有列表名称)

How can I write named list to files (with the list names) with purrr

我的列表中的每个(命名的)元素都是一个字符串。我怎样才能把这些字符串写在带有 purrr 的字符串上?

对于单个元素,我使用此代码:

cat(list[[1]], file = paste0(names(list)[1], ".txt"))

cat(list[[1]], file = names(list)[1]))

如果我直接用扩展名命名列表。

我希望一次写入所有文件。

imap 就是为此而构建的。

purrr::imap(lst, ~cat(.x, file = paste0(.y, ".txt")))

来自?imap

is short hand for map2(x, names(x))

所以你也可以做到

purrr::map2(lst, names(lst), ~cat(.x, file = paste0(.y, ".txt")))

或以 R 为基数

mapply(function(x, y) cat(x, file = paste0(y, ".txt")), lst, names(lst))

我们可以使用iwalk

library(purrr)
iwalk(lst, ~ cat(.x, paste0(.y, ".txt")))

或使用base R

lapply(names(lst), function(nm) cat(lst[[nm]], paste0(nm, ".txt")))