在R中自动读取zip文件

Joã*_*iel 24 compression r

我需要自动化R来读取一个zip文件中的csv数据文件.

例如,我会输入:

read.zip(file = "myfile.zip")
Run Code Online (Sandbox Code Playgroud)

在内部,将要做的是:

  • 解压缩myfile.zip到临时文件夹
  • 使用读取其中包含的唯一文件 read.csv

如果zip文件中有多个文件,则会引发错误.

我的问题是获取包含在zip文件中的文件的名称,在orded中提供它来执行read.csv命令.有谁知道怎么做?

UPDATE

这是我根据@Paul答案写的函数:

read.zip <- function(zipfile, row.names=NULL, dec=".") {
    # Create a name for the dir where we'll unzip
    zipdir <- tempfile()
    # Create the dir using that name
    dir.create(zipdir)
    # Unzip the file into the dir
    unzip(zipfile, exdir=zipdir)
    # Get the files into the dir
    files <- list.files(zipdir)
    # Throw an error if there's more than one
    if(length(files)>1) stop("More than one data file inside zip")
    # Get the full name of the file
    file <- paste(zipdir, files[1], sep="/")
    # Read the file
    read.csv(file, row.names, dec)
}
Run Code Online (Sandbox Code Playgroud)

由于我将使用更多文件tempdir(),我在其中创建了一个新的目录,所以我不会对文件感到困惑.我希望它可能有用!

Jos*_*ich 11

另一种解决方案unz:

read.zip <- function(file, ...) {
  zipFileInfo <- unzip(file, list=TRUE)
  if(nrow(zipFileInfo) > 1)
    stop("More than one data file inside zip")
  else
    read.csv(unz(file, as.character(zipFileInfo$Name)), ...)
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*tra 10

您可以使用unzip解压缩文件.我只是提到这一点,因为你的问题不清楚你是否知道这一点.关于阅读文件.一旦将文件解压缩到临时dir(?tempdir),只需用于list.files查找转储到临时目录中的文件.在您的情况下,这只是一个文件,您需要的文件.使用它阅读它read.csv非常简单:

l = list.files(temp_path)
read.csv(l[1])
Run Code Online (Sandbox Code Playgroud)

假设您的tempdir位置存储在temp_path.