2

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

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])

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

4

1 回答 1

1

这是一种使用我共同创作的两个包的方法(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来获取libraryorrequire调用。然后我们使用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这将确保安装了最低版本。

于 2015-03-20T15:29:48.693 回答