Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for installed packages before running install.packages() [duplicate]

Tags:

r

packages

People also ask

How do you check if a package is installed or not in R?

Calling installed. packages() returns a detailed data frame about installed packages, not only containing names, but also licences, versions, dependencies and more.

How do I check packages in R?

Start R within your package directory, load the devtools library with library(devtools) and then type check() , just as you had used build() and install() to build and install the package.

What does the installed packages () function do?

installed. packages scans the DESCRIPTION files of each package found along lib. loc and returns a matrix of package names, library paths and version numbers.

How do I list all packages in R?

To see what packages are installed, use the installed. packages() command. This will return a matrix with a row for each package that has been installed.


try: require("xtable") or "xtable" %in% rownames(installed.packages())


If you want to do it as simply as possible:

packages <- c("ggplot2", "dplyr", "Hmisc", "lme4", "arm", "lattice", "lavaan")

install.packages(setdiff(packages, rownames(installed.packages())))  

Replace the packages listed on the first line by those needed to run your code, and voilà!

Note: Edited to remove conditional wrapper thanks to Artem's comment below.


This is a function I often used to check for a package, install it otherwise and load again:

pkgTest <- function(x)
  {
    if (!require(x,character.only = TRUE))
    {
      install.packages(x,dep=TRUE)
        if(!require(x,character.only = TRUE)) stop("Package not found")
    }
  }

Works like pkgTest("xtable"). It only works if the mirror is set though, but you could enter that in the require calls.


I suggest a more lightweight solution using system.file.

is_inst <- function(pkg) {
    nzchar(system.file(package = pkg))
}

is_inst2 <- function(pkg) {
    pkg %in% rownames(installed.packages())
}

library(microbenchmark)
microbenchmark(is_inst("aaa"), is_inst2("aaa"))
## Unit: microseconds
##            expr      min        lq       mean    median       uq       max neval
##  is_inst("aaa")   22.284   24.6335   42.84806   34.6815   47.566   252.568   100
## is_inst2("aaa") 1099.334 1220.5510 1778.57019 1401.5095 1829.973 17653.148   100
microbenchmark(is_inst("ggplot2"), is_inst2("ggplot2"))
## Unit: microseconds
##                expr      min       lq     mean   median       uq      max neval
##  is_inst("ggplot2")  336.845  386.660  459.243  431.710  483.474  867.637   100
## is_inst2("ggplot2") 1144.613 1276.847 1507.355 1410.054 1656.557 2747.508   100