检索脚本中所需的库/包列表以实现可重现性

Retrieve list of libraries / packages required in a script for reproducibility

这是代码复现性的方便问题。您可能最终或收到一个长代码,其中包含在不同时间调用的各种自定义库(例如,在降价文档的各个部分)。假设您的文档构造不佳:

library(ggplot2)
# lots of lines of code
# and then more packages invoked, using both commands just spice things up
require(igraph) 
# lots of lines of code
library(pracma)
# lots of lines of code
# etc

是否有可能从代码中检索所有这些实例并将它们存储为列表的函数?

然后您可以更新脚本以包含注释行,供在不同工作区工作的任何人参考。

# To run this script first check if all libraries are installed and up to date.
# install.packages([results_of_an earlier_check])

当然可以从脚本中找到所有的库函数,但是将其自动化会更好,无论是构建您自己的脚本还是更新制作不佳的其他脚本。

这是一种使用我合着的两个包的方法(qdapRegex 来获取 library 调用和 pacman使其他人更容易使用脚本 运行):

首先,我将使用您的示例制作一个伪造的 .Rmd 文件,这样它更像您真正拥有的文件

temp <- paste(readLines(n=8), collapse="\n")
library(ggplot2)
# lots of lines of code
# and then more packages invoked, using both commands just spice things up
require(igraph) 
# lots of lines of code
library(pracma)
# lots of lines of code
# etc

cat(temp, file="delete_me.rmd")

现在我们可以读取它并使用 qdapRegex 来获取 libraryrequire 调用。然后我们使用 pacman 使脚本完全可重现:

rmd <- readLines("delete_me.rmd")

library(qdapRegex)
packs <- rm_between(rmd, c("library(", "require("), c(")", ")"), extract=TRUE)

boot <- 'if (!require("pacman")) install.packages("pacman")'
cat(paste0(boot, "\npacman::p_load(", paste(na.omit(unlist(packs)), collapse=", "), ")\n"))

这产生:

if (!require("pacman")) install.packages("pacman")
pacman::p_load(ggplot2, igraph, pracma)

您可以将其粘贴到脚本顶部的代码标记中,或使用散列使脚本可重现。如果你想确保加载了最新版本的包,请使用:p_install_version 这将确保安装了最小版本。