2012-09-17 32 views
44

我有一个非常大的zip文件,我试图把它读成R没有解压它像这样:R正在读取一个压缩数据文件,而无需解压就

temp <- tempfile("Sales", fileext=c("zip")) 
data <- read.table(unz(temp, "Sales.dat"), nrows=10, header=T, quote="\"", sep=",") 

Error in open.connection(file, "rt") : cannot open the connection 
In addition: Warning message: 
In open.connection(file, "rt") : 
    cannot open zip file 'C:\Users\xxx\AppData\Local\Temp\RtmpyAM9jH\Sales13041760345azip' 
+0

这篇文章可以帮助你:http://stackoverflow.com/questions/3053833/using-r-to-download-zipped-data-file-extract-and-import-data – Sam

+0

是的,我做了我尽职调查和搜查之前,我问这个问题,稍微不同的是,我想从我的本地文件系统读取,而不是通过一个URL。 – laiboonh

+0

你曾经解决过这个问题吗? –

回答

30

如果你的zip文件被称为Sales.zip和仅包含一个名为Sales.dat,我觉得你可以简单地做以下(假设该文件是在工作目录):

data <- read.table(unz("Sales.zip", "Sales.dat"), nrows=10, header=T, quote="\"", sep=",") 
+0

有没有办法找到“Sales.zip”文件中的文件名而不提取它? –

+0

@AllenWang是的,但是必须使用'unzip'函数:'unzip(“Sales.zip”,list = TRUE)' – plannapus

1

什么R版本您使用的?可能值得尝试最新的稳定版本(来自项目,而不是来自可能落后的发行版)。

我看到这个错误发生在旧版本中,但不是最新版本,当在两个版本中使用unz运行相同的命令时。

7

无需使用UNZ,如函数read.table现在可以直接处理压缩文件:

data <- read.table("Sales.zip", nrows=10, header=T, quote="\"", sep=",") 

this post

0

如果您ZCAT安装在系统上(这是Linux的情况下, ,macos和cygwin)您还可以使用:

zipfile<-"test.zip" 
myData <- read.delim(pipe(paste("zcat", zipfile))) 

此解决方案还具有不创建临时文件的优点。

2

如果文件后缀指示文件的性质,即以.gz,.bz2,.xz结尾的文件或.zip文件将被自动解压缩,readr软件包的方法也支持压缩文件。

require(readr) 
myData <- read_csv("foo.txt.gz")