-
-
Save gadenbuie/a90be17fc35f3d001393731ddd2f7175 to your computer and use it in GitHub Desktop.
find libraries used in your R scripts or Rmd documents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
find_used_libraries <- function(path = getwd(), include_rmd = FALSE, by_file = FALSE) { | |
library(tidyverse) | |
if (!requireNamespace('sessioninfo', quietly = TRUE)) { | |
install.packages("sessioninfo") | |
library(sessioninfo) | |
} | |
library_pattern <- paste( | |
"(?:library|require)\\((.+?)\\)", # pkgs via library, require, etc. | |
"requireNamespace\\(['\"](.+?)['\"].+?\\)", | |
"([[:alnum:]_]+):{2,3}[[:alnum:]_]+", # pkgs via pkgname::function() | |
sep = "|") | |
file_pattern <- paste0(".*\\.[Rr]", if (include_rmd) "(md|MD)?", "$") | |
x <- list.files(path, pattern = file_pattern, full.names = TRUE, recursive = TRUE) %>% | |
set_names() %>% | |
map(read_lines) %>% | |
map(~ paste(., collapse = " ")) %>% | |
map(~ str_match_all(., library_pattern)) %>% | |
map_df(~ data_frame(package = unique(c(.[[1]][, 3], .[[1]][, 4]))), .id = "file") %>% | |
filter(!is.na(package)) %>% | |
mutate(file = str_replace(file, getwd(), "")) | |
if (!by_file) x <- x %>% | |
group_by(package) %>% | |
count(sort = TRUE) %>% | |
rename(n_files = n) | |
x %>% | |
left_join(., sessioninfo::package_info(.$package), by = "package") %>% | |
select(-loadedversion, -path) %>% | |
select(package, contains('n_files'), version = ondiskversion, everything()) | |
} | |
#> find_used_libraries() | |
## # A tibble: 12 x 7 | |
## # Groups: package [12] | |
## package n_files version attached is_base date source | |
## <chr> <int> <chr> <lgl> <lgl> <chr> <chr> | |
## 1 lubridate 8 1.7.4 FALSE FALSE 2018-04-11 cran (@1.7.4) | |
## 2 purrr 8 0.2.4 TRUE FALSE 2017-10-18 CRAN (R 3.4.2) | |
## 3 here 6 0.1 FALSE FALSE 2017-05-28 CRAN (R 3.4.0) | |
## 4 stringr 3 1.3.0 TRUE FALSE 2018-02-19 CRAN (R 3.4.3) | |
## 5 DBI 2 0.8.0.9000 FALSE FALSE 2018-04-18 Github (r-dbi… | |
## 6 curl 1 3.2 FALSE FALSE 2018-03-28 CRAN (R 3.4.4) | |
## 7 dplyr 1 0.7.4 TRUE FALSE 2017-09-28 CRAN (R 3.4.2) | |
## 8 readr 1 1.1.1 TRUE FALSE 2017-05-16 CRAN (R 3.4.0) | |
## 9 RPostgres 1 1.1.0 FALSE FALSE 2018-04-18 Github (r-dbi… | |
## 10 tibble 1 1.4.2 TRUE FALSE 2018-01-22 CRAN (R 3.4.3) | |
## 11 tidyr 1 0.8.0 TRUE FALSE 2018-01-29 CRAN (R 3.4.3) | |
## 12 yaml 1 2.1.18 FALSE FALSE 2018-03-08 CRAN (R 3.4.4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment