Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download.file from url without specifying filename using R

Tags:

r

Am trying to download a file from a url. If I manually download and unzip it works fine, however, using download.file the zip is corrupt. I wonder if it is something to do with manually specifying the file name. Why is this neccesary when using the download.file function? Is it not possible to simply specify a url and folder and it download the file as it is named on the server?

##using R
##download url
url <- 'https://www.eea.europa.eu/data-and-maps/data/eea-reference-grids-2/gis-files/denmark-shapefile/at_download/file'

download.file(url, destfile ='Denmark_shapefile.zip')

unzip(zipfile = 'Denmark_shapefile.zip', exdir = '.')

Unzip fails as the file is corrupt

like image 610
Blaiso Avatar asked Oct 17 '25 03:10

Blaiso


2 Answers

destfile ='Denmark_shapefile.zip' is only specifying the name the downloaded file should have. You can write anything you want in there.

Since download.file in R doesn't read headers, like browsers do, it doesn't know the file name.

Your code works for me exactly as it is, but you could try using this download statement instead of yours which is specified for writing and is binary safe.

download.file(url, destfile ='Denmark_shapefile.zip', mode='wb', cacheOK=FALSE)
like image 176
tolik518 Avatar answered Oct 18 '25 20:10

tolik518


One way to do is,

    url <- 'https://www.eea.europa.eu/data-and-maps/data/eea-reference-grids-2/gis-
files/denmark-shapefile/at_download/file'

Your working directory is were files are downloaded

library(stringr)
fold = str_replace_all(getwd(), '/', '\\\\')

A random file name is assigned to zip file.

fil = tempfile(pattern = "file", tmpdir = fold, fileext = '.zip')
download.file(url, fil, mode = 'wb')
like image 35
Nad Pat Avatar answered Oct 18 '25 22:10

Nad Pat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!