安裝或加載 ggplot2、dplyr 等包時,控制台輸出:
Error in download.file(url, destfile, method, mode = "wb", ...) :
cannot open URL 'https://cran.r-project.org/src/contrib/PACKAGES.gz'
Warning: unable to access index for repository https://cran.r-project.org/src/contrib:
cannot open URL
或繪圖時因需下載字體/數據集而超時失敗。
R 默認 CRAN 鏡像指向 https://cran.r-project.org(海外服務器),國內直連極不穩定,導致下載元數據、包二進制文件、字體文件超時或被重置。
options(repos = c(CRAN = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
推薦鏡像:清華 https://mirrors.tuna.tsinghua.edu.cn/CRAN/、中科大 https://mirrors.ustc.edu.cn/CRAN/、阿里云 https://mirrors.aliyun.com/CRAN/。
.Rprofile 路徑:Sys.getenv("HOME")(Windows 通常在 C:/Users/用戶名/Documents/)。.Rprofile,追加:# 設置默認 CRAN 鏡像
local({
r <- getOption("repos")
r["CRAN"] <- "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"
options(repos = r)
})
Tools → Global Options → Packages → CRAN mirror → 選擇 "China (Tsinghua)" 或 "China (USTC)" → OK。
options(BioC_mirror = "https://mirrors.tuna.tsinghua.edu.cn/bioconductor/")
getOption("repos")
# 應輸出 CRAN 指向清華/中科大/阿里云鏡像地址
install.packages("ggplot2") # 應顯示從鏡像下載,速度飛快
options(repos=...) 覆蓋,以最後一次為準。pak、renv 等現代包管理器,它們有獨立配置文件(pak.json、renv.lock),需同步修改。options(repos = c(INTERNAL = "https://nexus:8081/repository/cran-proxy/"))。換源是 R 語言國內用戶的「必修課」,一次配置,終身受益。