Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load R package from character string

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?

like image 467
dynamo Avatar asked Jun 09 '11 09:06

dynamo


People also ask

What package is string() in in R?

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.

Which R function is used to load a package?

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.

How do I see loaded packages in R?

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.


1 Answers

Use the character.only argument

foo <- "ggplot2" library(foo,character.only=TRUE) 
like image 82
Sacha Epskamp Avatar answered Sep 21 '22 21:09

Sacha Epskamp