简体   繁体   中英

How do I name file downloads in R using data from another column in dataframe?

I have a large dataset of unique file IDs and links to download the files. It looks like this:

file_id <- c("id:fghjs12:ws8c7/syx", "id:f7gnsfu:7a6#*s", "id:dug:shxgcvu:6sh")
link <- c("https://www.dynare.org/wp-repo/dynarewp028.pdf", "https://www.dynare.org/wp-repo/dynarewp029.pdf", "https://www.dynare.org/wp-repo/dynarewp020.pdf")
df <- data.frame(file_id, link, stringsAsFactors = FALSE)

I want to download each file using the name of the handle. Some of the links are broken. So I have the following loop to do the task but it's not working..

download_documents <- function(url, file_id) {
   tryCatch(
     {download.file(url, paste0('~/Desktop/Dataset/files/', file_id))}, 
      error = function(e) {NA},
      warning = function(w) {NA})
}
Map(download_documents, df$link, df$file_id)

Does anyone know what I'm doing wrong or have a better solution? Thanks in advance for your help!

You can turn the file_id to valid names using make.names .

Map(download_documents, df$link, make.names(df$file_id))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM