Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download multiple files using "download.file" function

I am trying to download PDFs from a website using R.

I have a vector of the PDF-URLs (pdfurls) and a vector of destination file names (destinations):

e.g.:

pdfurls <- c("http://website/name1.pdf", "http://website/name2.pdf")
destinations <- c("C:/username/name1.pdf", "C:/username/name2.pdf")

The code I am using is:

for(i in 1:length(urls)){
    download.file(urls, destinations, mode="wb")}

However, when I run the code, R accesses the URL, downloads the first PDF, and repeats downloading the same PDF over and over again.

I have read this post: for loop on R function and was wondering if this has something to do with the function itself or is there a problem with my loop?

The code is similar to the post here: How to download multiple files using loop in R? so I was wondering why it is not working and if there is a better way to download multiple files using R.

like image 364
eylemyap Avatar asked Dec 25 '22 02:12

eylemyap


1 Answers

I think your loop is mostly fine, except you forgot to index the urls and destinations objects.

Tangentially, I would recommend getting in the habit of using seq_along instead of 1:length() when defining for loops.

for(i in seq_along(urls)){
    download.file(urls[i], destinations[i], mode="wb")
}

Or using Map as suggested by @docendodiscimus :

Map(function(u, d) download.file(u, d, mode="wb"), urls, destinations)
like image 195
Benjamin Avatar answered Jan 05 '23 02:01

Benjamin