Search code examples
runzip

Read a zip file in r


I want to read a zip file from the web, my code is as followed

temp<-tempfile()
download<-download.file("http://depts.washington.edu/control/LARRY/TE/IDVs/idv1.zip",temp)
data<-read.table(unz(temp,"r.dat"),head=FALSE)
unlink(temp)

But it shows an error

Error in open.connection(file, "rt") : cannot open the connection
In addition: Warning message:
In open.connection(file, "rt") :
  cannot locate file 'r.dat' in zip file 'C:\Users\CHENGF~2\AppData\Local\Temp\RtmpgtJShr\file361c5d0a55eb'

I don't know why it can't read the data, hope someone can help me!


Solution

  • this works for all the idv files except the idv1 which appears to be corrupted. You would need to unzip idv1.zip using another tool and read it in...

    readrdat <- function(n) {
        fname <- paste0("idv",n)
        zipname <- paste0(fname,".zip")
        weblink <- paste0("http://depts.washington.edu/control/LARRY/TE/IDVs/",zipname)
        download.file(weblink,zipname)
        data <- read.table(unz(zipname,paste0(fname,"/r.dat")),header=FALSE)
        unlink(zipname)
        return(data)
    } #readrdat
    
    lsdata <- lapply(1:15, function(n) {
        tryCatch(readrdat(n), error=function(e) NULL)
    })
    lapply(lsdata, is.null)