OganM
OganM

Reputation: 2663

Installing and loading packages with a single function

I have been trying to write a function to replace library and install.packages functions of R that loads the functions if it is installed and installs and loads if it is not. It works fine for the first case but when I try to install a function using this even after installing it gives the 'there is no package called ...' error. The packages get installed correctly but I failed to install and load in the single run of the same function. I added the sleep command hoping it would fix it but it did not. Anyone know why?

insist = function(name){
    #enables entering package name without quotes
    name = substitute(name) 
    name = as.character(name)

    if (!require(name, character.only = T)) {
        install.packages(name)
        Sys.sleep(2)
        library(name, character.only = T)
    }
}

Upvotes: 2

Views: 1031

Answers (1)

MrFlick
MrFlick

Reputation: 206167

That message is actually coming from require() and not install.packages() or library(). I bet the package it still being added to your search path (at least it was for me). So I think you have to be more aggressive about suppressing that warning. Try this.

insist = function(name){
    #enables entering package name without quotes
    name = substitute(name) 
    name = as.character(name)

    if (suppressWarnings(!require(name, character.only = T, quietly=T))) {
        install.packages(name)
        library(name, character.only = T)
    }
}

Upvotes: 2

Related Questions