使用 R 循环下载文件并重命名

Using R to loop through downloading of files and renaming it

我想从 url 列表中下载多个文件。有些网址可能无效,如果有错误我想跳过它。 如果可以的话,也想根据ID给下载的文件重命名。

如果有人能帮助我,我将不胜感激。我的数据样本如下:

ID <- c('L18491','K18781','I28004')
url <- c('https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_50.xlsx',
         'https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_101.xlsx',
         'https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_100.xlsx')


df <- data.frame(ID, url)

我们可以使用 possibly 来自 purrr

library(purrr)    
out_lst <- map(df$url, pfun)
names(out_lst) <- df$ID 

哪里

pfun <- possibly(f1, otherwise = NA)

哪里

f1 <- function(urllink) {
      openxlsx::read.xlsx(urllink)
 }

或者另一种选择是 tryCatch

f2 <-  function(urllink) {

      tryCatch(openxlsx::read.xlsx(urllink), 
             error = function(e) message("error occured"))
}
out_lst2 <- lapply(df$url, f2)

如果我们想使用download.file

lapply(seq_along(df$url), function(i)
        tryCatch(download.file(df$url[i], paste0(getwd(), "/", df$ID[i], ".xlsx")),
              error = function(e) message("error occured")))
              

或使用iwalk

library(tibble)
pfun2 <- possibly(download.file, otherwise = NA)
iwalk(deframe(df), ~ pfun2(.x, as.character(glue::glue('{getwd()}/{.y}.xlsx'))))

您可以使用download.file下载文件并根据ID变量命名。

Map(function(x, y) tryCatch(download.file(x, sprintf('%s.xlsx', y)), 
                            error = function(e) {}, 
                            warning = function(w) {}), df$url, df$ID)

这将下载您工作目录中的文件并将其命名为 ID.xlsx。它还会跳过生成的任何错误或警告。