我无法下载文件,我如何更新下面的函数,如果我打印一些值FILE_NAMES,它们是空的.会出什么问题呢?

# Set the download URL
url <- "https://ftp.ncbi.nlm.nih.gov/pub/pmc/manuscript/xml/"

# Create a vector of file numbers to download
file_nums <- sprintf("%02d", 1:3) 

# Create a pattern to match the beginning of the file names
pattern <- paste0("^author_manuscript_xml.PMC0", file_nums)

# Get a vector of all file names from the URL and filter based on the pattern
file_names <- grep(pattern, list.files(url), value = TRUE)

# Loop through the file names and download each file
for (file_name in file_names) {
  file_url <- paste0(url, file_name)
  download.file(file_url, file_name)
}

推荐答案

下面的代码解决了这个问题.诀窍是遍历pattern,而不是文件名.

suppressPackageStartupMessages({
  library(rvest)
  library(dplyr)
})

# create a temp dir where to download the files
tmpdir <- tempdir()
tmpdir <- chartr("\\", "/", tmpdir)

# Create a vector of file numbers to download
file_nums <- sprintf("%02d", 1:3) 

# Create a pattern to match the beginning of the file names
pattern <- paste0("^author_manuscript_xml.PMC0", file_nums)

# this is the page link
link <- "https://ftp.ncbi.nlm.nih.gov/pub/pmc/manuscript/xml/"

# read the page only once
page <- read_html(link)

# extract all links
file_names <- page %>%
  html_elements("a") %>%
  html_attr("href")

# this is probably necessary, some files are 1G+
old_opts <- options(timeout = max(600, getOption("timeout")))

# download the files
res <- lapply(pattern, \(p) {
  i <- grep(p, file_names)
  files <- file_names[i]
  urls <- paste0(link, files)
  destfls <- paste(tmpdir, files, sep = "/")
  mapply(\(u, d) {
    tryCatch(download.file(u, d), error = function(e) e)
  }, urls, destfls)
})

# restore the default timeout
options(old_opts)

R相关问答推荐

在' geom_contour_filled()'中对齐两个gplot的 colored颜色 比例

用apply/map/etch替换循环以加快速度

如何设置搜索栏来搜索整个Shiny应用程序页面?

过滤Expand.Grid的结果

R中的枢轴/转置

使用scale_x_continuous复制ggplot 2中的离散x轴

如何使用geom_sf在边界显示两种 colored颜色 ?

使用sensemakr和fixest feols模型(R)

在特定列上滞后n行,同时扩展框架的长度

更新合适的R mgcv::bam模型报告无效类型(关闭).'';错误

咕噜中的元素列表:map

terra nearest()仅为所有`to_id`列返回NA

用黄土法确定区间

如何在格子中添加双曲曲线

在ggplot中为不同几何体使用不同的 colored颜色 比例

绘制采样开始和采样结束之间的事件

DEN扩展包中的RECT树形图出现异常行为

根据纬度和距离连接两个数据集

如何计算每12行的平均数?

按组和连续id计算日期差