【问题标题】:Using R to loop through downloading of files and renaming it使用 R 循环下载文件并重命名
【发布时间】:2021-01-17 17:41:26
【问题描述】:

我想从 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)

【问题讨论】:

  • 当您说重命名时,是要重命名的列还是创建具有该 ID 的对象

标签: r excel loops download


【解决方案1】:

我们可以从purrr使用possibly

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'))))

【讨论】:

  • 如何将文件下载到wd中?
  • @Jane 将帖子更新为download.file
  • 我试过了,但它没有将 xlsx 文件下载到我指定的文件夹中。
  • @Jane 为此,您需要在 df$ID[i] 之前指定“wd”pasteed,即 paste0(getwd(), df$ID[i], ".xlsx")
  • 谢谢,但我确实注意到在目标文件夹中,有文件出现然后消失。已检查,文件名中没有重复。知道为什么吗?
【解决方案2】:

您可以使用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。它还会跳过生成的任何错误或警告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    相关资源
    最近更新 更多