2011-06-09 102 views
22

我想創建一個函數,其中包括加載函數內的一個包。一個簡短的例子(不運行!):從字符串中加載R包

loadMe <- function(name){ 
    genLib(xxx, libName = name) #make a new library with name "name" 
    library(name)    #load the new library... 
} 

這是行不通的!可重複的代碼有點這說明我的主要問題:

library(ggplot)   #this works fine 
load.this <- "ggplot" 
library(load.this)  #I want this to load ggplot! 

我知道這個問題是library()require()當作參數,其尚不存在的對象名稱。我已經試過包裝我的字符串,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 

有沒有辦法做到這一點?

+0

如果您看看庫('?library')的幫助,那麼您得到了(在參數部分中):''package'作爲名稱給出的包的名稱或文字字符串或字符串,具體取決於「character.only」是否爲「FALSE」(默認)或「TRUE」。 – Marek 2011-06-09 10:54:39

回答

32

使用character.only參數

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

你說,你已經使用parse()嘗試。以下內容似乎適用於我:

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

避免解析。使用替代替代 – hadley 2011-06-09 14:18:40

+0

@hadley:爲什麼要避免'parse'?如何在這種情況下獲得「替代品」以取得相同的結果?當我不知道事先知道哪個庫應該被加載時,我正在考慮這種情況,儘管我可能會把它作爲一個文本字符串。 – nullglob 2011-06-14 09:22:29

+4

您始終想要使用提供問題最佳表示的對象類型。要使用替代品你會這樣做:'替代(庫(pkg),列表(pkg = as.name(「MASS」)))' – hadley 2011-06-14 14:30:22