如何在我创建的函数中导入多个R包?

时间:2019-06-21 21:11:07

标签: r

我具有此功能,该功能旨在安装和加载多个软件包,以便一次性运行整个脚本。 但是从我可以看到的方式来看,软件包仅每隔两次加载一次,有时该功能只是安装了它们,而没有加载。 我该如何解决?非常感谢您的任何答复。

install_load_packages=function(packages){
  install.packages(c("data.table","rentrez","worms","bold","stringr","readr","fingerprint","seqRFLP","dplyr","ggplot2"))
  library(seqRFLP)
  library(bold)
  library(data.table)
  library(rentrez)
  library(worms)
  library(stringr)
  library(readr)
  library(fingerprint)
  library(dplyr)
  library(ggplot2)
}
install_load_packages(packages)

1 个答案:

答案 0 :(得分:0)

如果您想自己编写代码,可以使用类似以下内容的

load.libraries <- c("data.table","rentrez","worms","bold","stringr","readr","fingerprint","seqRFLP","dplyr","ggplot2")
install.lib <- load.libraries[!load.libraries %in% installed.packages()]
for(libs in install.lib) install.packages(libs, dependences = TRUE)
sapply(load.libraries, require, character = TRUE)

如果您喜欢使用pacman软件包(如我所建议),则可以这样使用:

if (!require("pacman")) install.packages("pacman")
packages <- c("data.table","rentrez","worms","bold","stringr","readr","fingerprint","seqRFLP","dplyr","ggplot2")
pacman::p_load(char = packages)