我怎么能一次加载一堆包,而不需要一遍又一遍地键入要求命令?我尝试了三种方法,都失败了。
基本上,我想为一个函数提供一个包名向量,该函数将加载它们。
x<-c("plyr", "psych", "tm")
require(x)
lapply(x, require)
do.call("require", x)
我怎么能一次加载一堆包,而不需要一遍又一遍地键入要求命令?我尝试了三种方法,都失败了。
基本上,我想为一个函数提供一个包名向量,该函数将加载它们。
x<-c("plyr", "psych", "tm")
require(x)
lapply(x, require)
do.call("require", x)
当前回答
另一个选项来自软件包easypackages(需要安装)。你可以用最直观的方式加载包:
library("easypackages")
libraries("plyr", "psych", "tm")
该包还包括一个安装几个包的函数:
packages("plyr", "psych", "tm")
参考这里。
其他回答
基于daroczig的解决方案,如果不想指定一个列表作为输入,可以使用
# Foo
mLoad <- function(...) {
sapply(sapply(match.call(), as.character)[-1], require, character.only = TRUE)
}
# Example
mLoad(plyr, dplyr, data.table)
... 它比
lapply(list('plyr', 'dplyr', 'data.table'), require, character.only = TRUE)
轻微修改Tyler Rinker的回答,增加安装和加载吃豆人的检查:
#Install/load pacman
if(!require(pacman)){install.packages("pacman");require(pacman)}
#Install/load tons of packages
p_load(plyr,psych,tm)
我喜欢p_load解决方案,因为它避免了引用!
另一个选项来自软件包easypackages(需要安装)。你可以用最直观的方式加载包:
library("easypackages")
libraries("plyr", "psych", "tm")
该包还包括一个安装几个包的函数:
packages("plyr", "psych", "tm")
参考这里。
我认为@daroczig提供的代码可以通过用库替换require并将lapply调用包装在invisible()函数内部来改进。因此,改进后的代码将如下所示:
invisible(lapply(x, library, character.only = TRUE))
这段代码得到了改进,因为:
library() is generally preferred over require() for loading packages because the former gives an error if the package is not installed while the latter just gives a warning. Moreover, require() calls library(), so why not just use library() directly! library("time") # Error in library("time") : there is no package called ‘time’ require("time") # Loading required package: time # Warning message: # In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : # there is no package called ‘time’ The list object returned and printed by the lapply() call is not meaningful in this case, so it makes sense to make the output invisible. Say you use R Notebook for your analysis work, using the invisible() function will suppress the contents of the list object and prevent the clutter in the rendered notebook file.
我维护的CRAN包pacman(与Dason Kurkiewicz合著)可以实现这一点:
所以用户可以这样做:
## install.packages("pacman")
pacman::p_load(dplyr, psych, tm)
如果包丢失,p_load将从CRAN或Bioconductor下载它。