-1

I need a command to check if a package in installed in R and if not then installs it and load the library.

Probably like

If package="xyz" is installed then "do nothing" else "install package" and "library"

I tried system.file(package="xyz"), but it just give the path. May be the command I need should give an "TRUE" or "FALSE" status and the actions can be followed.

Thanks

zephryl
  • 14,633
  • 3
  • 11
  • 30

2 Answers2

1

There are multiple ways to test whether a package is installed, e.g. via:

length(find.package(pkg, quiet = TRUE)) > 0L

But the easiest (and conventional) way is to simply try to load the package, and then install it if that fails:

if (! requireNamespace(pkg, quietly = TRUE)) {
    install.packages(pkg)
    loadNamespace(pkg)
}

That said, I would caution against using this solution in most scenarios (and likewise I would not advise using packages that implement this mechanism, such as ‘pacman’). Instead, package installation and running scripts should generally be separate responsibilities (for example, on some systems, although this tends to be rare, only admins are allowed to install packages!). Instead, executable code should declare its dependencies out of line and provide an installation script.

Unfortunately R doesn’t provide a lot of support for this out of the box, unless you wrap your code inside a package. For other projects, the state of the art for dependency management in R is provided by ‘renv’.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • In particular, the "conventional" solution above intentionally avoids `installed.packages()` because that function does a lot of work that's unnecessary here, and is *very slow*. – Konrad Rudolph Mar 02 '23 at 09:22
1

As mentioned, multiple ways exist to check if packages are installed and load them. I prefer using the p_load function in the 'pacman' package.

pacman::p_load(pkg1, pkg2, pkg3, pkg4, pk5)

see more here: https://cran.r-project.org/web/packages/pacman/index.html