我怎么能一次加载一堆包,而不需要一遍又一遍地键入要求命令?我尝试了三种方法,都失败了。
基本上,我想为一个函数提供一个包名向量,该函数将加载它们。
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)
当前回答
对于那些想要同时安装和加载包的人来说,我从这个链接中遇到了这个函数
# ipak function: install and load multiple R packages.
# check to see if packages are installed. Install them if they are not, then load them into the R session.
ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
# usage
packages <- c("ggplot2", "plyr", "reshape2", "RColorBrewer", "scales", "grid")
ipak(packages)
其他回答
你所提议的函数的几种排列是可行的——但前提是你指定了字符。唯一的论点为真。简单的例子:
lapply(x, require, character.only = TRUE)
对于那些想要同时安装和加载包的人来说,我从这个链接中遇到了这个函数
# ipak function: install and load multiple R packages.
# check to see if packages are installed. Install them if they are not, then load them into the R session.
ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
# usage
packages <- c("ggplot2", "plyr", "reshape2", "RColorBrewer", "scales", "grid")
ipak(packages)
您可以简单地使用lubripack包,它整齐地安装新包,然后在一行中加载所有这些包。
lubripack("plyr", "psych", "tm")
下面是在RStudio中运行上述代码后的输出。
软件包安装方法:
运行下面的代码下载包并从GitHub安装。不需要有GitHub帐户。
library(devtools)
install_github("espanta/lubripack")
轻微修改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解决方案,因为它避免了引用!
这应该可以达到目的:
lapply(x, FUN = function(X) {
do.call("require", list(X))
})
(关键是do中的args参数。Call (what, args)必须是一个列表——即使它只有一个元素!)