Telaroz
Telaroz

Reputation: 258

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

Each (named) element of my list is a character string. How can I write those strings at ones with purrr?

For a single element I use this code:

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

or

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

if I name the list directly with the extension.

I expect to write all files at once.

Upvotes: 2

Views: 3370

Answers (2)

akrun
akrun

Reputation: 887691

We can use iwalk

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

Or using base R

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

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 389175

imap is build for this.

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

From ?imap

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

So you can also do

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

Or in base R

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

Upvotes: 3

Related Questions