Skip to contents

This function attempts to load multiple R packages specified by the user. If a package is not installed, the function can optionally install it before loading. It also provides an option to print the names and versions of the loaded packages.

Usage

load_packages(
  ...,
  package_list = NULL,
  verbose = FALSE,
  install_missing = FALSE
)

Arguments

...

Character. Names of the packages to be loaded or installed.

package_list

Character vector. An alternative or additional way to specify package names as a vector.

verbose

Logical. If TRUE, prints the names and versions of the loaded packages. Defaults to FALSE.

install_missing

Logical. If TRUE, missing packages are automatically installed and then loaded. Defaults to FALSE.

Value

This function is used for its side effects (loading/installing packages) and does not return any value.

Author

Ahmed El-Gabbas

Examples

# Currently loaded packages
(P1 <- ecokit::loaded_packages())
#>  [1] "qs2"       "arrow"     "car"       "carData"   "rworldmap" "raster"   
#>  [7] "sp"        "purrr"     "terra"     "fs"        "tibble"    "png"      
#> [13] "sf"        "ggplot2"   "dplyr"     "ecokit"    "magrittr"  "stats"    
#> [19] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     

# Load tidyr
load_packages(tidyr, raster, ggplot2, verbose = TRUE)
#> The following packages were already loaded:
#>   >>>>  ggplot2 (3.5.2)
#>   >>>>  raster (3.6-32)
#> Loading packages:
#>   >>>>  tidyr (1.3.1)

# Loaded packages after implementing the function
(P2 <- ecokit::loaded_packages())
#>  [1] "tidyr"     "qs2"       "arrow"     "car"       "carData"   "rworldmap"
#>  [7] "raster"    "sp"        "purrr"     "terra"     "fs"        "tibble"   
#> [13] "png"       "sf"        "ggplot2"   "dplyr"     "ecokit"    "magrittr" 
#> [19] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
#> [25] "base"     

# Which packages were loaded?
setdiff(P2, P1)
#> [1] "tidyr"

# verbose = FALSE (default)
load_packages(tidyterra, verbose = FALSE)

# load already loaded packages
load_packages(tidyr, tidyterra, verbose = TRUE)
#> The following packages were already loaded:
#>   >>>>  tidyr (1.3.1)
#>   >>>>  tidyterra (0.7.2)

# non-existent package
load_packages("non_existent")
#> The following packages are neither available nor installed as install_missing = FALSE:
#>   >>>>   non_existent