3

I need to download some csv files from "http://www.elections.state.md.us".

And here is my code.

url <- "http://www.elections.state.md.us/elections/2012/election_data/index.html"
# recognize the links
links <- getHTMLLinks(url)
filenames <- links[str_detect(links,"_General.csv")]
filenames_list <- as.list(filenames)
filenames
# create a function
downloadcsv <- function(filename,baseurl,folder){
  dir.create(folder,showWarnings = FALSE)
  fileurl <- str_c(baseurl,filename)
  if(!file.exists(str_c(folder,"/",filename))){
    download.file(fileurl,
                  destfile = str_c(folder,"/",filename))
    # 1 sec delay between files
    Sys.sleep(1)
  }
}
library(plyr)
l_ply(filenames_list,downloadcsv,
      baseurl = "www.elections.state.md.us/elections/2012/election_data/",
      folder = "elec12_maryland")

The error comes out as :

Error in download.file(fileurl, destfile = str_c(folder, "/", filename)) : scheme not supported in URL 'www.elections.state.md.us/elections/2012/election_data/State_Congressional_Districts_2012_General.csv'

However, when I try to paste the url into the IE and it did work. So what is the problem of my code?

Any idea would be helpful,Thx.

1 Answer 1

5

It turns out that the url must start with a scheme such as http://, https://, ftp:// or file://. So in the last line, I changed the code to

l_ply(filenames_list,downloadcsv,
      baseurl = "http://www.elections.state.md.us/elections/2012/election_data/",
      folder = "elec12_maryland")

And it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.