ohnoplus
ohnoplus

Reputation: 1335

Have a function that calls library and takes either a package or its name as input in R

When I start up and R script and I like to check their package versions. I tend to run something like

 library(dplyr); packageVersion("dplyr")

This works fine, but I'd like to shorten this to a single function that would load a library and then return its version.

I want the libary function to accept either a string of the library name, or just the library name typed in by itself.

I tried this function:

libver <- function(pac){
    if(!is.character(pac)){
         pac <- deparse(substitute(pac))
        }
    library(pac, character.only=TRUE)
    packageVersion(pac)
    }

But this works for string inputs but not non string inputs

 libver(MASS)

Error in libver(MASS): object 'MASS' not found

I can hard code it to take objects rather than strings as follows,

libver <- function(pac){
    library( deparse(substitute(pac), character.only=TRUE)
    packageVersion(deparse(substitute(pac))
    }

but I'd like to keep the flexability to do either one if I can.

Upvotes: 2

Views: 122

Answers (2)

eipi10
eipi10

Reputation: 93871

!is.character(pac) returns an error when pac is the bare package name, without quotation marks. Instead, you can do pac = as.character(substitute(pac)) which will return a character string, regardless of whether the argument was originally a character string.

libver <- function(pac) {

  pac = as.character(substitute(pac))

  library(pac, character.only=TRUE)
  packageVersion(pac)

}

Upvotes: 3

moodymudskipper
moodymudskipper

Reputation: 47350

libver <- function(pac){
  pac <- gsub("\"","",deparse(substitute(pac)))
    library(pac,character.only = T)
    packageVersion(pac)
}

libver(dplyr)
[1] ‘0.7.2’
libver("dplyr")
[1] ‘0.7.2’

Upvotes: 2

Related Questions