Calling on the content of an object, and not the name of the object. Or renaming the object the name of the content of said object

StackOverflow https://stackoverflow.com/questions/22598251

Question

So my goal is to create a function that will first try to load a package. If it cannot be loaded it will then try to install it and then load it. I saw this type of code somewhere and I used it in a couple of my functions, where I always specified the necessary packages within the functions. I figured this would be a nice tool to generalize into a function. There are so many packages I often forget what I already have installed.

The issue is that in lib and lib2 it passing the name of the object("package") and not the name of the contents of the object ("SpatialPack"). I've tried a few things like specifying the location within the object ("package[1]"), but that did nothing.

Any help in getting it to call to the content of the object, and not the name of the object would be awesome. Thanks!

  get.package<-function(package){
  lib<-require(package)
  if(lib==TRUE)
  {
    print(paste(c(package,"Package successfully loaded")))
  }
 if(lib==FALSE)
 {
 print(paste(c("Attempting to install and load",package,"Package")))
 install.packages(package)
 lib2<-require(package)
 if (lib2==TRUE)
 {
 print(paste(c(package,"Package successfully installed and loaded")))
 }
 else print(paste(c(package,"Package unable to be installed")))

 }
 }

 get.package("SpatialPack")
Was it helpful?

Solution

Both require and library do non-standard evaluation as a convenience, but you can suppress this with a parameter. Try changing your code to:

 require(package,  character.only = TRUE)

Demonstration:

> strangeName <- "sets"
> require(strangeName, character.only=TRUE)
Loading required package: sets

Attaching package: ‘sets’

The following object is masked from ‘package:data.table’:

    set
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top