I want to create a function which includes loading a package that I make within the function. A short example (which doesn't run!):
loadMe <- function(name){
genLib(xxx, libName = name) #make a new library with name "name"
library(name) #load the new library...
}
This does not work! A bit of reproducible code which illustrates my main problem:
library(ggplot) #this works fine
load.this <- "ggplot"
library(load.this) #I want this to load ggplot!
I know the problem is that library()
and require()
take as an argument an object name which does not exist yet. I have tried wrapping my character string with parse()
, deparse()
, substitute()
, expression()
, quote()
, etc etc. These all return the same problem:
library(load.this)
# Error in library(loadss) : there is no package called 'loadss'
library(deparse(load.this))
# Error in library(deparse(loadss)) : 'package' must be of length 1
Is there a way to do this?
The stringr package provide a cohesive set of functions designed to make working with strings as easy as possible. If you're not familiar with strings, the best place to start is the chapter on strings in R for Data Science.
There are basically two extremely important functions when it comes down to R packages: install. packages() , which as you can expect, installs a given package. library() which loads packages, i.e. attaches them to the search list on your R workspace.
You can use the packageVersion() function to print version information about the loaded packages. To print the version information about R, the OS and attached or loaded packages, use the sessionInfo() function.
Use the character.only
argument
foo <- "ggplot2" library(foo,character.only=TRUE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With