2012-09-17 34 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")