Reputation: 258
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
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
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