packages

usage

Whenever possible, use pack::fun() instead of library("pack") ; fun(). It makes clear from wich package ‘fun’ is used.
Otherwise, when multiple packages have fun, the one from the lastly loaded package will be used. And that might not be the one you expect.
When you use multiple functions from a package, the second option is fine of course.

installation

Installing add-on R packages usually is easy from within R (and works without admin rights):

install.packages("ggplot2")

For potential installation issues, see below.

At the top of a script, conditionally install all needed packages.

For a single package, you could use

if(!requireNamespace("berryFunctions", quietly=TRUE)) install.packages("berryFunctions")

To depend on a certain development version, use

if(packageVersion("berryFunctions") < "1.19.3")
  {
  if(!requireNamespace("remotes", quietly=TRUE)) install.packages("remotes")
  remotes::install_github("brry/berryFunctions")
  }

When using several packages, use

if(!requireNamespace("pacman", quietly=TRUE)) install.packages("pacman")
pacman::p_load("berryFunctions", "rdwd")

issues

Here are solutions to some issues I have encountered in the past while installing packages with external (i.e. non-R) dependencies.

rJava on Windows

Check if Java is available. There should be no errors when running (in R):

install.packages("rJava") ; library(rJava)

If necessary, install Java in the same bit-version as R (eg 64bit). The Java binary file must be on the search path, which will normally happen automatically.

In case you run into the 32/64 bits error: “JAVA_HOME cannot be determined from the Registry”, try installing the package with no multiarchitecture support, e.g.: remotes::install_github("brry/OSMscale", build_opts="--no-multiarch")

rJava on Linux

Open a terminal (CTRL+ALT+T) and paste (CTRL+SHIFT+V) all lower-cased:

sudo apt-get install r-cran-rjava

Here’s the list of other supported packages using this mechanism.
You might first have to run something like (source):

sudo add-apt-repository ppa:c2d4u.team/c2d4u4.0+

sf

If install.packages("sf") on Linux does not work, you can try the following:

sudo apt-get install libudunits2-dev
sudo add-apt-repository ppa:ubuntugis/ppa && sudo apt-get update
sudo apt-get install gdal-bin
sudo apt install libgdal-dev libproj-dev

See also thinkr.fr on R4 on Ubuntu 20.04

gdal

Probably obsolete with the retirement of rgdal, but just for reference:

sudo apt update
sudo apt install libgdal-dev libproj-dev

source

If you cannot install a package, you might be able to source some functions.
Download the package zip folder on github (see git) and then run:

Vectorize(source)(dir("unzipped_package_path/R", full=TRUE))

This creates all R functions as objects in your globalenv workspace (and overwrites existing objects of the same name!).