Loading multiple R packages with a single command

喜你入骨 提交于 2020-08-08 05:13:42

问题


Multiple R packages may be loaded using the function p_load function from pacman R package with the following command:

pacman::p_load("ggplot2", "lme4")

However, I want to use the command like this

Packages <- c("ggplot2", "lme4")
pacman::p_load(Packages)

which does not work. Wonder how this can be achieved?


回答1:


Set character.only on TRUE

Packages <- c("ggplot2", "lme4")
Packages %in% loadedNamespaces() # check if the packages are loaded
# [1] FALSE FALSE

pacman::p_load(Packages, character.only = TRUE)

Packages %in% loadedNamespaces()
# [1] TRUE TRUE

From ?p_load:

"character.only : logical. If TRUE then p_load will only accept a single input which is a character vector containing the names of packages to load."




回答2:


Alternatively, do do.call(p_load, packages).

You can also do this without Pacman:

lapply(packages, require, character.only = TRUE)

But as others have said, not recommended because it reduces clarity.




回答3:


Use argument char in p_load function.

char: Character vector containing packages to load

foo <- c("data.table", "ggplot2")
pacman::p_load(char = foo)


来源:https://stackoverflow.com/questions/45509485/loading-multiple-r-packages-with-a-single-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!