eylemyap eylemyap - 1 month ago 15
R Question

Downloading multiple files using "download.file" function in R

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):


[1] "http://website/name1.pdf"

[2] "http://website/name2.pdf"



[1] "C:/username/name1.pdf"

[2] "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.


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")