I’m looking to download a gzipped csv and load it as an R object without saving it first to disk. I can do this with zipped files but can’t seem to get it to work with gzfile or gzcon.
Example:
grabRemote <- function(url) {
temp <- tempfile()
download.file(url, temp)
aap.file <- read.csv(gzfile(temp), as.is = TRUE)
unlink(temp)
return(aap.file)
}
grabRemote("http://dumps.wikimedia.org/other/articlefeedback/aa_combined-20110321.csv.gz")
That downloads a (small) gz compressed file containing Wikipedia article feedback data (not important, but just to indicate it isn’t giant or nefarious).
The code I have works fine but I feel like I’m missing something very obvious by resorting to creating and destroying a temporary file.
I am almost certain I answered this question once before. The upshot is that Connections API of R (
file(),url(),pipe(), …) can do decompression on the fly, I do not think you can do it for remote http objects.So do the very two-step you have described: use
download.file()with atempfile()result as second argument to fetch the compressed file, and then read from it. Astempfile()object, it will get cleaned up automatically at the end of your R session so the one minor fix I can suggest is to skip theunlink()(but then I like explicit cleanups, so you may as well keep it).Edit: Got it:
The key was the hint the
gzconhelp that it can put decompression around an existing stream. We then need the slight detour ofreadLinesand reading viatextConnectionfrom that asread.csvwants to go back and forth in the data (to validate column width, I presume).