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条回答
Juvenile、少年°
2楼-- · 2020-01-22 13:26

Sure.

You need to compare 'installed packages' with 'desired packages'. That's very close to what I do with CRANberries as I need to compare 'stored known packages' with 'currently known packages' to determine new and/or updated packages.

So do something like

AP <- available.packages(contrib.url(repos[i,"url"]))   # available t repos[i]

to get all known packages, simular call for currently installed packages and compare that to a given set of target packages.

查看更多
beautiful°
3楼-- · 2020-01-22 13:26

Quite basic one.

pkgs = c("pacman","data.table")
if(length(new.pkgs <- setdiff(pkgs, rownames(installed.packages())))) install.packages(new.pkgs)
查看更多
再贱就再见
4楼-- · 2020-01-22 13:26
library <- function(x){
  x = toString(substitute(x))
if(!require(x,character.only=TRUE)){
  install.packages(x)
  base::library(x,character.only=TRUE)
}}

This works with unquoted package names and is fairly elegant (cf. GeoObserver's answer)

查看更多
在下西门庆
5楼-- · 2020-01-22 13:27
source("https://bioconductor.org/biocLite.R")
if (!require("ggsci")) biocLite("ggsci")
查看更多
老娘就宠你
6楼-- · 2020-01-22 13:28
if (!require('ggplot2')) install.packages('ggplot2'); library('ggplot2')

"ggplot2" is the package. It checks to see if the package is installed, if it is not it installs it. It then loads the package regardless of which branch it took.

查看更多
别忘想泡老子
7楼-- · 2020-01-22 13:28

I have implemented the function to install and load required R packages silently. Hope might help. Here is the code:

# Function to Install and Load R Packages
Install_And_Load <- function(Required_Packages)
{
    Remaining_Packages <- Required_Packages[!(Required_Packages %in% installed.packages()[,"Package"])];

    if(length(Remaining_Packages)) 
    {
        install.packages(Remaining_Packages);
    }
    for(package_name in Required_Packages)
    {
        library(package_name,character.only=TRUE,quietly=TRUE);
    }
}

# Specify the list of required packages to be installed and load    
Required_Packages=c("ggplot2", "Rcpp");

# Call the Function
Install_And_Load(Required_Packages);
查看更多
登录 后发表回答