Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

r - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...