R/tool_check_dependency.R

Defines functions .check_dependency

.check_dependency <- function(pkg_names, algorithm_name) {
  
  # Check availability for each package without loading them
  # sapply returns a named logical vector
  is_available <- sapply(pkg_names, requireNamespace, quietly = TRUE)
  
  # Identify the names of missing packages
  missing_pkgs <- names(is_available[!is_available])
  
  # nocov start
  # Proceed only if there are missing packages
  if (length(missing_pkgs) > 0) {
    
    # Format package names for the error message
    missing_pkgs_str <- paste(missing_pkgs, collapse = ", ") 
    # e.g., "GA, DEoptim"
    install_cmd_pkgs <- paste0("'", missing_pkgs, "'", collapse = ", ") 
    # e.g., "'GA', 'DEoptim'"
    
    # Construct a helpful error message
    error_message <- sprintf(
      "Package(s) required for %s are missing: %s.\n
      Please install %s using:\n\ninstall.packages(c(%s))",
      algorithm_name,
      missing_pkgs_str,
      ifelse(length(missing_pkgs) > 1, "them", "it"), 
      # Use "them" or "it" appropriately
      install_cmd_pkgs
    )
    
    # Stop execution and display the message
    # call. = FALSE prevents the function call trace from being part of the error message
    stop(error_message, call. = FALSE)
  }
  # nocov end
  
  # If the check passes for all packages, return TRUE invisibly
  invisible(TRUE)
}

Try the multiRL package in your browser

Any scripts or data that you put into this service are public.

multiRL documentation built on March 31, 2026, 5:06 p.m.