简体   繁体   English

从字符串加载 R package

[英]Load R package from character string

I want to create a function which includes loading a package that I make within the function.我想创建一个 function,其中包括加载我在 function 中制作的 package。 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.我知道问题在于library()require()将 object 名称作为参数,该名称尚不存在。 I have tried wrapping my character string with parse() , deparse() , substitute() , expression() , quote() , etc etc. These all return the same problem:我尝试用parse()deparse()substitute()expression()quote()等包装我的字符串。这些都返回相同的问题:

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使用character.only参数

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

You say that you have tried using parse() .您说您尝试过使用parse() The following seems to work for me:以下似乎对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM