Skip to content

Instantly share code, notes, and snippets.

@PietrH
Created July 8, 2024 10:04
Show Gist options
  • Save PietrH/4185804a84975ade2ff938fa64a303a8 to your computer and use it in GitHub Desktop.
Save PietrH/4185804a84975ade2ff938fa64a303a8 to your computer and use it in GitHub Desktop.
check for similarly named function arguments in an R package
Library(dplyr)
# Which package to check
trias_namespace <- asNamespace("trias")
# Character vector of all functions and their arguments, print method of base ls with str() on every object
trias_fns_args <- capture.output(utils::lsf.str(trias_namespace))
# Extract the functions
trias_functions <- stringr::str_extract(trias_fns_args, ".+(?= :)") %>%
.[!is.na(.)]
# Extract their arguments
trias_arguments <-
stringr::str_extract_all(
stringr::str_c(trias_fns_args, collapse = " "),
stringr::regex("(?<=function \\().*?\\)", dotall = TRUE, multiline = TRUE)
) %>%
purrr::map(~ stringr::str_remove(.x, "\\)$")) %>%
purrr::map(~ stringr::str_split(.x, stringr::fixed(","))) %>%
purrr::map(~ purrr::map(.x, stringr::str_squish)) %>%
purrr::flatten()
# Create a tibble with one row per argument, also column with the arguments
# witout defaults (not foolproof)
trias_fns_args_tbbl <-
tibble(trias_functions, trias_arguments) %>%
tidyr::unnest(trias_arguments) %>%
mutate(arg_only = stringr::str_remove(trias_arguments, " .+$"))
# Cluster based on string disntance
hc <-
stringdist::stringdistmatrix(trias_fns_args_tbbl$arg_only,
trias_fns_args_tbbl$arg_only) %>%
as.dist() %>%
hclust(method = "average")
# Reorder our tibble so the most similar arguments are together
trias_fns_args_tbbl[hc$order, ]
@PietrH
Copy link
Author

PietrH commented Jul 8, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment