开发者

Load R package from character string

开发者 https://www.devze.com 2023-03-11 06:49 出处:网络
I want to create a function which includes loading a package that I make within the function.A short example (which doesn\'t run!):

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()开发者_StackOverflow 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?


Use the character.only argument

foo <- "ggplot2"
library(foo,character.only=TRUE)


You say that you have tried using parse(). The following seems to work for me:

eval(parse(text = 'library(MASS)')[1])
0

精彩评论

暂无评论...
验证码 换一张
取 消