R语言访问NCBI FTP站点不稳定问题求助
提升R语言访问NCBI FTP资源的稳定性方案
问题描述
我用R语言从NCBI获取生物信息学资源,近几个月访问稳定性持续下降。运行以下代码大多失败:
readr::read_tsv("https://ftp.ncbi.nlm.nih.gov/refseq/H_sapiens/Homo_sapiens.gene_info.gz")
报错信息:
Error in open.connection(3L, "rb") : Could not resolve host: ftp.ncbi.nlm.nih.gov
偶尔(包括今天)代码能正常运行,且浏览器可直接下载该文件,确认服务器可用——这只是众多不稳定问题中的一个示例。由于报错即时返回无超时,排除服务器过载问题,求提升访问稳定性的方法。
系统环境信息
R version 4.2.2 (2022-10-31) Platform: x86_64-apple-darwin21.6.0 (64-bit) Running under: macOS Monterey 12.6 Matrix products: default BLAS: /usr/local/Cellar/openblas/0.3.21/lib/libopenblasp-r0.3.21.dylib LAPACK: /usr/local/Cellar/r/4.2.2/lib/R/lib/libRlapack.dylib locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] devtools_2.4.5 usethis_2.1.6 loaded via a namespace (and not attached): [1] Rcpp_1.0.9 pillar_1.8.1 compiler_4.2.2 later_1.3.0 [5] urlchecker_1.0.1 prettyunits_1.1.1 profvis_0.3.7 remotes_2.4.2 [9] tools_4.2.2 bit_4.0.5 digest_0.6.31 pkgbuild_1.4.0 [13] pkgload_1.3.2 tibble_3.1.8 memoise_2.0.1 lifecycle_1.0.3 [17] pkgconfig_2.0.3 rlang_1.0.6 shiny_1.7.3 cli_3.4.1 [21] curl_4.3.3 parallel_4.2.2 fastmap_1.1.0 withr_2.5.0 [25] stringr_1.5.0 fs_1.5.2 htmlwidgets_1.5.4 vctrs_0.5.1 [29] hms_1.1.2 tidyselect_1.2.0 bit64_4.0.5 glue_1.6.2 [33] R6_2.5.1 processx_3.8.0 fansi_1.0.3 vroom_1.6.0 [37] sessioninfo_1.2.2 tzdb_0.3.0 callr_3.7.3 purrr_0.3.5 [41] readr_2.1.3 magrittr_2.0.3 ps_1.7.2 promises_1.2.0.1 [45] ellipsis_0.3.2 htmltools_0.5.4 mime_0.12 xtable_1.8-4 [49] httpuv_1.6.7 utf8_1.2.2 stringi_1.7.8 miniUI_0.1.1.1 [53] cachem_1.0.6 crayon_1.5.2
解决方法
1. 切换DNS服务器
报错核心是主机解析失败,优先更换稳定的公共DNS:
- macOS操作:打开「系统设置」-「网络」- 选中当前网络点击「详细信息」-「DNS」,添加
8.8.8.8(Google DNS)或1.1.1.1(Cloudflare DNS),并移至列表顶部。
2. 实现自动重试逻辑
用重试机制封装请求,解决偶发的解析失败问题:
library(purrr) library(readr) safe_read <- safely(read_tsv) result <- retry( safe_read("https://ftp.ncbi.nlm.nih.gov/refseq/H_sapiens/Homo_sapiens.gene_info.gz"), when = function(x) inherits(x$error, "error") && grepl("Could not resolve host", x$error$message), max_tries = 5, delay = 1 ) df <- if (!is.null(result$result)) result$result else stop("多次重试仍无法访问")
3. 检查并配置R网络代理
如果你的环境需要代理,确认R的代理设置正确:
- 查看当前代理:
Sys.getenv(c("http_proxy", "https_proxy")) - 设置代理:
Sys.setenv(https_proxy = "http://your-proxy:port")(替换为实际代理地址)
4. 本地缓存常用资源
对于频繁使用的资源,下载到本地后读取,避免重复远程请求:
local_path <- "Homo_sapiens.gene_info.gz" if (!file.exists(local_path)) { download.file("https://ftp.ncbi.nlm.nih.gov/refseq/H_sapiens/Homo_sapiens.gene_info.gz", local_path) } df <- read_tsv(local_path)
内容的提问来源于stack exchange,提问作者Ngwenyama
相关产品推荐
相关产品推荐

