Skip to content

Instantly share code, notes, and snippets.

@johnbaums
Last active September 10, 2024 05:01
Show Gist options
  • Save johnbaums/c7711c2c55cb9f21fcaae30e025ffb2f to your computer and use it in GitHub Desktop.
Save johnbaums/c7711c2c55cb9f21fcaae30e025ffb2f to your computer and use it in GitHub Desktop.
Get the unique set of namespaces specified in an R script
get_namespaces <- function(file, as_imports=FALSE) {
require(stringi)
require(dplyr)
nm <- readLines(file) %>%
stringi::stri_extract_all(regex='[\\w_.]+::[\\w_.]+') %>%
unlist %>%
setdiff(NA) %>%
sort
if(as_imports) {
imports <- strsplit(nm, '::')
if(!length(imports)) return(NULL)
imports %>%
do.call(rbind.data.frame, .) %>%
setNames(c('ns', 'fun')) %>%
group_by(ns) %>%
summarise(
string = sprintf("#' @importFrom %s %s",
cur_group(), paste(fun, collapse=' ')),
.groups='drop'
) %>%
pull(string) %>%
cat(sep='\n')
} else {
nm
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment