簡體   English   中英

使用 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)

我們可以使用possiblypurrr

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 它還將跳過生成的任何錯誤或警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM