Elegant way to check for missing packages and inst

2020-01-22 13:20发布

I seem to be sharing a lot of code with coauthors these days. Many of them are novice/intermediate R users and don't realize that they have to install packages they don't already have.

Is there an elegant way to call installed.packages(), compare that to the ones I am loading and install if missing?

标签: r packages r-faq
27条回答
趁早两清
2楼-- · 2020-01-22 13:52

Dason K. and I have the pacman package that can do this nicely. The function p_load in the package does this. The first line is just to ensure that pacman is installed.

if (!require("pacman")) install.packages("pacman")
pacman::p_load(package1, package2, package_n)
查看更多
我只想做你的唯一
3楼-- · 2020-01-22 13:52

Regarding your main objective " to install libraries they don't already have. " and regardless of using " instllaed.packages() ". The following function mask the original function of require. It tries to load and check the named package "x" , if it's not installed, install it directly including dependencies; and lastly load it normaly. you rename the function name from 'require' to 'library' to maintain integrity . The only limitation is packages names should be quoted.

require <- function(x) { 
  if (!base::require(x, character.only = TRUE)) {
  install.packages(x, dep = TRUE) ; 
  base::require(x, character.only = TRUE)
  } 
}

So you can load and installed package the old fashion way of R. require ("ggplot2") require ("Rcpp")

查看更多
再贱就再见
4楼-- · 2020-01-22 13:53

Using lapply family and anonymous function approach you may:

  1. Try to attach all listed packages.
  2. Install missing only (using || lazy evaluation).
  3. Attempt to attach again those were missing in step 1 and installed in step 2.
  4. Print each package final load status (TRUE / FALSE).

    req <- substitute(require(x, character.only = TRUE))
    lbs <- c("plyr", "psych", "tm")
    sapply(lbs, function(x) eval(req) || {install.packages(x); eval(req)})
    
    plyr psych    tm 
    TRUE  TRUE  TRUE 
    
查看更多
登录 后发表回答