Search code examples
rcran

Avoid being asked for CRAN mirror?


When running R from the terminal, we sometimes see

--- Please select a CRAN mirror for use in this session ---

Is there a universal, efficient, and memorable way to install.packages("example") without needing to memorise urls or interact with a dialogue box?

That is, is there a way to install an R package which is:

  1. universal (works on any/all installations of R, irrespective of operating system)
  2. Requires no memorisation of url(s)
  3. Requires no interaction with duologue box(es)
  4. Requires no files (e.g. .Rprofile) to be created or edited

Lastly, ideally, a method which is short and memorable (or easy use without having to look it up).

Here's a pseudo code example of an ideal solution (where 'force' is pseudocode for 'choose the most obvious defaults and press on at all costs!)

force(install.packages("example"))

Solution

  • If you run help("install.packages"), you can see that the default value for the repository is repos = getOption("repos"). If you follow this trail to help("getOption"), it provides some more insight. Here is what it says for the repos option.

    repos:

    URLs of the repositories for use by update.packages. Defaults to c(CRAN="@CRAN@"), a value that causes some utilities to prompt for a CRAN mirror. To avoid this do set the CRAN mirror, by something like local({r <- getOption("repos"); r["CRAN"] <- "http://my.local.cran"; options(repos = r)}).

    You can see this by going into the 'etc/' subdirectory of your R installation. There is a file there called 'repositories'. While some other repos (e.g., R-Forge) have default URLs, CRAN does not. It shows @CRAN@ as referenced by the help file.

    The R documentation advises you that some utilities, such as what you are experiencing at the command line, will prompt you for a mirror, unless the option is explicitly set. The documentation does not indicate an alternative work around.

    The reason why there cannot be a function to tell it to use the "most obvious default" is that there is actually no default. So a method such as your hypothetical force() would not be possible.


    An edit with a bit more info:

    You can use a few helpers from utils to set the repos option. I am not sure if it is easy enough to remember for your criteria, but there is chooseCRANmirror() and getCRANmirrors().

    # this should work
    chooseCRANmirror(ind = 1)
    install.packages("example")
    
    # or this clunky approach
    install.packages("example", repos = getCRANmirrors()[1,"URL"])
    

    But honestly at that point you may be better off just remembering repos = https://cloud.r-project.org/.