Samantha Sullivan Samantha Sullivan - 3 months ago 19
R Question

How to download file that has a changing file name in R

I am trying to download a file into R using this code:

temp<-tempfile()
temp2<-tempfile()
download.file("http://WEBSITENAMEHERE_160828.full.rdb.gz",temp)
gunzip(temp, temp2)


This code allows the file to be downloaded an unzipped, BUT the "160828" part will change every 7 days to update the data. Meaning, in 7 days, the file will be called "160904" Is there a way for R to automatically change that date every 7 days, or will the user manually have to change it?

Thank you!

Answer

Try this

tmp <- as.numeric(gsub(x = seq.Date(from = as.Date("16-08-28"),to = as.Date("16-10-04"),by = "week"),pattern = "-",replacement = ""))
#[1] 160828 160904 160911 160918 160925 161002

It will take care of the numeric part and use paste function to create the full download link.

paste0("http://WEBSITENAMEHERE_",tmp,".full.rdb.gz")
#[1] "http://WEBSITENAMEHERE_160828.full.rdb.gz"
#[2] "http://WEBSITENAMEHERE_160904.full.rdb.gz"
#[3] "http://WEBSITENAMEHERE_160911.full.rdb.gz"
#[4] "http://WEBSITENAMEHERE_160918.full.rdb.gz"
#[5] "http://WEBSITENAMEHERE_160925.full.rdb.gz"
#[6] "http://WEBSITENAMEHERE_161002.full.rdb.gz"