Gen
Gen

Reputation: 23

How to save a list into a zip archive in R?

I want to save each element of a list as a txt file and save all of txt files in a zip folder. I was able to create a function that currently saves element of the list into a txt file. Sample list could look like this:

enter image description here

I found that gzfile and readr allow creating zip for a single file. For eg

write_tsv(mtcars, file.path(dir, "mtcars.tsv.gz"))
#OR
write.csv(mtcars, file=gzfile("mtcars.csv.gz"))

Whereas, I want to be able to create a zip folder that contains data1.txt, data2.txt and data.txt. Are there any packages that would allow this?

Upvotes: 0

Views: 536

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

You can use zip() from base R to zip your text files. Something like this:

file_names = paste0(names(your_list), ".txt")
for(i in seq_along(your_list)) {
  write_tsv(your_list[[i]], file.path(dir, file_names[i]))
}
zip(file.path(dir, "zipped_files.zip"), files = file.path(dir, file_names))

Upvotes: 1

Related Questions