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’.