Q:

Get a list of all packages loaded in all .Rmd files in a directory

Suppose I have 2 (or any number of) .Rmd files in ~/directory1/. In each file, I load several R packages using library(packagename). How can I get a character vector containing the names of all unique packages loaded in all of these files?

A:

#setwd(~/directory1/)
libs = lapply(list.files(pattern = "\\.Rmd$"),
              function(x){
                  d = readLines(x)
                  d = d[grepl("library\\(.*\\)", d)]
                  gsub("library\\((.*)\\)", "\\1", d)
              })
unique(unlist(libs))

