Skip to content

Instantly share code, notes, and snippets.

@AliciaSchep
Created February 19, 2018 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AliciaSchep/5cd2274d46648df8f782d109c190173a to your computer and use it in GitHub Desktop.
Save AliciaSchep/5cd2274d46648df8f782d109c190173a to your computer and use it in GitHub Desktop.
Find the r packages used in directory
get_r_files <- function(path = ".", recursive = FALSE, include_rmd = TRUE){
all_files <- normalizePath(list.files(path, full.names = TRUE,
recursive = recursive))
r_files <- grep(".*\\.(r|R)$", all_files, value = TRUE)
if (include_rmd){
r_files <- c(r_files,
grep(".*\\.(r|R)md$", all_files, value = TRUE))
}
return(r_files)
}
get_pkgs_used <- function(filename){
lines <- readr::read_file(filename)
regex_libraries <-
stringr::str_c(c(
purrr::map_chr(c("library",
"require",
"loadNamespace",
"requireNamespace"),
~stringr::str_c("(?<=",.,
"\\()[^[\\)]]+(?=\\))")),
"[[:alnum:]\\.]+(?=\\:\\:)"),
collapse = "|")
libs <- unlist(stringr::str_extract_all(lines,regex_libraries))
libs <- stringr::str_trim(libs)
libs <- stringr::str_replace_all(libs,'\\"','')
libs <- stringr::str_replace_all(libs,"\\'|\\`",'')
unique(libs)
}
find_dependencies <- function(path = ".", recursive = FALSE, include_rmd = TRUE){
r_files <- get_r_files(path = path,
recursive = recursive,
include_rmd = include_rmd)
unique(unlist(purrr::map(r_files, get_pkgs_used)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment