Check if package is installed without loading

时间:2018-09-18 20:20:47

标签: r r-package

The typical way a package developer is advised to check whether a user has installed a package is like this:

if (!requireNamespace("package")) {
  stop("Please install package.")
}

requireNamespace loads the package (in the current scope?) and returns a TRUE/FALSE value. I need to check the install state of a package without loading the namespace.

The reason for this is because I am writing a knit_print S3 method (extending the knitr package) and the namespace I am checking for kableExtra has side effects outside of the context of my knit_print method that I want to avoid.

When loaded, kableExtra changes how subsequent calls to knitr::kable are formatted at the global level. It has good reasons for doing so, but I want to use kableExtra inside my S3 method and not have end users confused about why kable behaves differently after my knit_print method is called.

That's why I want to do the check for the namespace (and if kableExtra is not installed, just call knitr::normal_print) without loading the namespace.

Edit: To clarify why I don't think this is a duplicate of this question, those answers do not pay any special attention to whether the solution loads the package when it is installed. It turns out that some of the solutions do not load the package in question, but they are not clearly differentiated.

1 个答案:

答案 0 :(得分:2)

Use installed.packages.

if ("kableExtra" %in% rownames(installed.packages()) {
    # do something
}