R语言报错:未设置CRAN镜像导致contrib.url()执行失败
解决R语言安装dplyr时的CRAN镜像未设置报错
报错信息
Error in `contrib.url()`: ! trying to use CRAN without setting a mirror Backtrace: 1. utils::install.packages("dplyr", dependencies = TRUE) 2. utils::contrib.url(repos, "source") Execution halted
问题场景
原本为解决“找不到recode函数”问题安装dplyr,运行以下代码后无法编译(knit):
protestag<-recode(Event.tag,'Education'= 1, 'Executive' = 2, 'Racial Injustice' = 3, 'Collective Bargaining'= 4, 'Healthcare' = 5, 'Environment' = 6, 'Civil Rights'= 7) install.packages("dplyr",dependencies = TRUE) library(dplyr)
解决方案
1. 临时设置镜像(单次生效)
调用install.packages()时直接指定镜像地址,国内推荐清华镜像:
install.packages("dplyr", dependencies = TRUE, repos = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/")
2. 永久设置镜像(全局生效)
运行以下代码配置后,每次启动R都会自动加载镜像:
# 弹出可视化窗口选择镜像 chooseCRANmirror() # 或手动写入配置,立即生效 options(repos = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) # 保存到R配置文件,永久生效 file.edit("~/.Rprofile") # 在打开的文件中添加一行:options(repos = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")),保存退出即可
3. R Markdown编译注意事项
- 建议提前在本地R环境安装好dplyr,再进行knit,避免在文档中重复执行安装命令。
- 若必须在文档中安装,需先设置镜像再执行安装:
options(repos = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) install.packages("dplyr", dependencies = TRUE) library(dplyr)
额外修正:函数调用顺序
你的代码中recode函数调用在加载dplyr之前,这会导致“找不到函数”的错误,正确顺序应为:
library(dplyr) protestag<-recode(Event.tag,'Education'= 1, 'Executive' = 2, 'Racial Injustice' = 3, 'Collective Bargaining'= 4, 'Healthcare' = 5, 'Environment' = 6, 'Civil Rights'= 7)
内容的提问来源于stack exchange,提问作者Aly
相关产品推荐
相关产品推荐

