<- function(sizes = FALSE) {
lib_summary if (!is.logical(sizes)) {
stop("'sizes' must be logical (TRUE/FALSE).")
}
<- utils::installed.packages()
pkgs <- table(pkgs[, "LibPath"])
pkg_tbl <- as.data.frame(pkg_tbl, stringsAsFactors = FALSE)
pkg_df names(pkg_df) <- c("Library", "n_packages")
if (sizes) {
library("fs")
$lib_size <- vapply(
pkg_df$Library,
pkg_dffunction(x) {
sum(file_size(dir_ls(x, recurse = TRUE)))
},FUN.VALUE = numeric(1)
)
}
pkg_df }
Managing dependencies ๐
This is how we might use another package in a script:
But this is how we do it in a package:
use_package("fs")
Use fs
in our function:
<- function(sizes = FALSE) {
lib_summary <- utils::installed.packages()
pkgs <- table(pkgs[, "LibPath"])
pkg_tbl <- as.data.frame(pkg_tbl, stringsAsFactors = FALSE)
pkg_df names(pkg_df) <- c("Library", "n_packages")
if (sizes) {
$lib_size <- vapply(
pkg_df$Library,
pkg_dffunction(x) {
sum(fs::file_size(fs::dir_ls(x, recurse = TRUE)))
},FUN.VALUE = numeric(1)
)
}
pkg_df }
test() # failure for unused argument
Update tests
test_that("lib_summary fails appropriately", {
expect_error(lib_summary(sizes = "foo"), "not interpretable as logical")
})
test_that("sizes argument works", {
<- lib_summary(sizes = TRUE)
res expect_equal(names(res), c("Library", "n_packages", "lib_size"))
expect_type(res$lib_size, "double")
})
check() # will warn about undocumented parameter
Update documentation
Ctrl+Alt+Shift+R will insert the spot for the sizes param
#' Provides a brief summary of the package libraries on your machine
#'
#' @param sizes Should the sizes of the libraries be calculated?
#' Logical; default `FALSE`.
#'
#' @return A data.frame containing the count of packages in each of the user's
#' libraries. A `lib_size` column is included if `sizes = TRUE`.
#' @export
#'
#' @examples
#' lib_summary()
#' lib_summary(sizes = TRUE)
document()
check()
Alternative: use importFrom
use_import_from("purrr", "map_dbl")
Use map_dbl()
directly without namespace qualifier:
<- function(sizes = FALSE) {
lib_summary <- utils::installed.packages()
pkgs <- table(pkgs[, "LibPath"])
pkg_tbl <- as.data.frame(pkg_tbl, stringsAsFactors = FALSE)
pkg_df names(pkg_df) <- c("Library", "n_packages")
if (sizes) {
$lib_size <- map_dbl(
pkg_df$Library,
pkg_df~ sum(fs::file_size(fs::dir_ls(.x, recurse = TRUE)))
)
}
pkg_df }