使用R优雅的处理压缩文件

本节介绍在R中如何生成zip,tar.gz等格式的压缩文件,并批量读取压缩文件,废话不多说直接开干

安装并加载R包

package.list=c("tidyverse","archive","readr")

for (package in package.list) {
  if (!require(package,character.only=T, quietly=T)) {
    install.packages(package)
    library(package, character.only=T)
  }
}

csv转zip文件

write_csv(mtcars, archive_write("mtcars.zip", "mtcars.csv"))

读入zip压缩文件

read_csv(archive_read("mtcars.zip"), col_types = cols())

csv转tar.gz文件

write_csv(mtcars, archive_write("mtcars.tar.gz", "mtcars.csv",
                                options = "compression-level=9"))

读入tar.gz文件

read_csv(archive_read("mtcars.tar.gz"), col_types = cols())

多个文件同时打包为压缩文件

write_csv(iris, "iris.csv")
write_csv(mtcars, "mtcars.csv")
write_csv(airquality, "airquality.csv")

archive_write_files("data.tar.gz", c("iris.csv", "mtcars.csv", "airquality.csv"))

按文件名读取文件

a <- archive("data.tar.gz")

read_csv(archive_read(a, file = 1), col_types = cols())
read_csv(archive_read(a, file = "mtcars.csv"), col_types = cols())

你可能感兴趣的:(使用R优雅的处理压缩文件)