2

This is a question of convenience on code reproducibility. You may end up or receive a long code with various custom libraries called at various times (e.g. in various sections of a markdown document). Suppose you have a poorly constructed document:

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

Is there a function to possibly retrieve all these instances from the code, and store them as a list for example?

Then you could update the script to include a commented line to be used as reference for anyone working in a different workspace.

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

Of course it is possible to find all the library functions from the script, but it would be even better to automatize this, both for framing your own scripts or updated poorly made others.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
puslet88
  • 1,288
  • 15
  • 25

1 Answers1

1

Here's an approach using two packages I have co-authored on (qdapRegex to grab the library calls & pacman to make the script easier for others to run):

First I'm going to use your example to make a fake .Rmd file so it'S's more like what you've really got

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

Now we can read it in and use qdapRegex to grab the library or require calls. Then we use pacman to make the script fully reproducible:

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

This yields:

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

You can paste this at the top of the script in code tags or use the hash to make the script reproducible. If you want to make sure recent versions of a package are loaded use: p_install_version which will make sure the minimal version is installed.

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519