从字符串加载R包 [英] Load R package from character string

查看:158
本文介绍了从字符串加载R包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,其中包括加载我在该函数内的包。一个简短的示例(不运行!):

  loadMe<  -  function(name){
genLib (xxx,libName = name)#make一个名为name的新库
library(name)#加载新库...
}

这不行!有一点可重现的代码,说明我的主要问题:

  library(ggplot)#this工作正常
load.this < - ggplot
库(load.this)#我想要加载ggplot!

我知道问题是 library() require()将不存在的对象名作为参数。我尝试用 parse() deparse() expression() quote()同样的问题:

 库(load.this)
#库中的错误'loadss'
库(deparse(load.this))
#库中的错误(deparse(loadss)):'package'必须长度为1



有办法吗?

解决方案

使用 character.only 参数

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


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?

解决方案

Use the character.only argument

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

这篇关于从字符串加载R包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆