在 R 中设置永久的默认 CRAN 镜像

问题描述 投票:0回答:3

如何在 R 中永久设置特定的 CRAN 镜像?

我想将其永久设置在我的笔记本电脑中,这样当我这样做时

install.packages()
,它就不会再次询问我选择哪个镜子。

r cran r-faq
3个回答
153
投票

您可以在 .Rprofile 中设置 repos 以在每次启动 R 时恢复您的选择

编辑:更准确地说:

添加

options(repos=c(CRAN="THE URL OF YOUR FAVORITE MIRROR"))

到您的 .Rprofile,位于您用户的主目录中。

您可以在此处找到 CRAN 镜像列表。

示例

# add this line to ~/.Rprofile, restart your R session so it takes effect
options(repos=c(CRAN="http://cran.r-project.org"))

或者,您可以在

Rprofile.site
中设置站点范围内的镜像。文件的位置由
?Startup
:

给出

的 该文件的路径取自

R_PROFILE
的值 环境变量(波浪号扩展后)。如果这个变量是 未设置,默认为
R_HOME/etc/Rprofile.site
,如果 它存在(在“出厂时”安装中不存在)。

对于第一个选项,请执行

Sys.getenv("R_PROFILE")
,对于第二个选项,请执行
Sys.getenv("R_HOME")
R.home()
。在 macOS 上,第二个位置是
/Library/Frameworks/R.framework/Resources/etc/

该文件可能不存在,或者您可能会看到以下行被注释掉:

# set a CRAN mirror
# local({r <- getOption("repos")
#       r["CRAN"] <- "http://my.local.cran"
#       options(repos=r)})

因此删除注释标记并将“http://my.local.cran”更改为正确的网站,例如:

local({r <- getOption("repos")
       r["CRAN"] <- "http://cran.r-project.org"
       options(repos=r)})

1
投票

在一种情况下,上面建议的 .Rprofile 编辑不起作用。然而,下面的代码却做到了:

utils::setRepositories(ind = 0, addURLs = c(CRAN = "YOUR FAVORITE MIRROR"))

其中“YOUR FAVORITE MIRROR”是 URL,而不是名称。

编辑 .Rprofile 后重新启动 R。

ind = 0
将指示您只需要指定的存储库。其他存储库可以包含在
addURLs =
选项中,并在字符向量中以逗号分隔。


-1
投票

如果您尝试在 RStudio 中执行此操作,您可以通过 RStudio UI(工具 -> 全局选项 -> 包)执行此操作,也可以使用文件

~/.config/rstudio/rstudio-prefs.json
并将以下内容放入
https://cran.rstudio.com/
中。

{
    "cran_mirror": {
        "name": "Global (CDN)",
        "host": "RStudio",
        "url": "https://cran.rstudio.com/",
        "country": "us",
        "ok": 1,
        "secondary": ""
    }
}

可能您已经设置了其他选项,因此您只需将

cran_mirror
添加到列表中即可。

我当前系统上的完整文件(

RStudio Server 2022.02.2 Build 485
Ubuntu 20.04.4 LTS
)如下所示:

{
    "initial_working_directory": "~",
    "margin_column": 120,
    "scroll_past_end_of_document": true,
    "highlight_r_function_calls": true,
    "rainbow_parentheses": true,
    "posix_terminal_shell": "bash",
    "default_project_location": "~",
    "jobs_tab_visibility": "shown",
    "source_with_echo": true,
    "save_workspace": "never",
    "load_workspace": false,
    "always_save_history": false,
    "data_viewer_max_columns": 500,
    "cran_mirror": {
        "name": "Global (CDN)",
        "host": "RStudio",
        "url": "https://cran.rstudio.com/",
        "country": "us",
        "ok": 1,
        "secondary": ""
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.