### Package Setup with usethis Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Initializes version control, connects to GitHub, sets up continuous integration, and configures a pkgdown website for the package. ```r # Initialize version control usethis::use_git() # Connect to GitHub usethis::use_github() # Set up continuous integration usethis::use_github_action("check-standard") # Set up pkgdown website usethis::use_pkgdown_github_pages() ``` -------------------------------- ### Build, Check, and Install VIP Package with R CMD Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Provides R CMD commands for building the source package, checking it against CRAN standards, and installing it. Also shows how to generate documentation using roxygen2. ```bash # Build source package R CMD build . # Check package (CRAN standards) R CMD check vip_*.tar.gz --as-cran # Install package R CMD INSTALL . # Generate documentation (alternative to devtools::document()) Rscript -e "roxygen2::roxygenise()" ``` -------------------------------- ### Install VIP Package with Vignettes Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Installs the VIP package along with its vignettes. Vignettes provide extended examples and documentation for package features. ```r devtools::install(build_vignettes = TRUE) ``` -------------------------------- ### R Install Package Locally with devtools Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Shows how to install an R package locally using `devtools::install()`. This command compiles and installs the package into the R library, making it available for use in R sessions. It's a fundamental step in the development workflow for testing the package as if it were installed from a repository. ```r # Install package locally devtools::install() ``` -------------------------------- ### R Build Source and Binary Packages with devtools Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Demonstrates how to build source and binary R packages using `devtools::build()`. The command `devtools::build()` creates a source package (`.tar.gz`), while `devtools::build(binary = TRUE)` creates a platform-specific binary package. These commands are used to prepare the package for distribution and installation. ```r # Build source package (.tar.gz) devtools::build() # Build binary package devtools::build(binary = TRUE) ``` -------------------------------- ### R Load All Package Code with devtools Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Illustrates how to use `devtools::load_all()` in R to load all package code, simulating installation and loading. This command is a key part of the iterative development cycle, allowing developers to quickly test changes without a full package build and install. It's often associated with the RStudio keyboard shortcut Ctrl/Cmd + Shift + L. ```r # Load all package code (Ctrl/Cmd + Shift + L) devtools::load_all() # This simulates installing and loading the package # Much faster than build + install during development ``` -------------------------------- ### Conditional Testing for Dependencies in R Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md An example of conditional testing in R using tinytest. This pattern ensures that tests requiring optional dependencies (like 'randomForest' or 'pdp') are only run if those packages are installed and available. ```r # Always check dependencies before running tests exit_if_not( requireNamespace("randomForest", quietly = TRUE), requireNamespace("pdp", quietly = TRUE) ) ``` -------------------------------- ### TDD: Adding New Model Support in R Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Example of writing tests first for adding support for a new machine learning model in the vip package. It demonstrates checking dependencies, fitting a model, and asserting the structure and content of the variable importance scores returned by the vi() function. ```r # Example: Adding new model support # File: inst/tinytest/test_pkg_newmodel.R # Check dependencies first exit_if_not(requireNamespace("newmodel", quietly = TRUE)) # Load test data data("test_dataset") # Fit model model <- newmodel::fit_model(target ~ ., data = test_dataset) # Test vi() method vi_scores <- vi(model) expect_inherits(vi_scores, c("vi", "tbl_df", "tbl", "data.frame")) expect_equal(nrow(vi_scores), ncol(test_dataset) - 1L) expect_true(all(c("Variable", "Importance") %in% names(vi_scores))) ``` -------------------------------- ### Run VIP Package Tests with tinytest Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Executes all tests for the VIP package using the tinytest framework. It also shows how to run a specific test file and check package coverage. ```r # Run all tests tinytest::test_package("vip") # Run specific test file tinytest::run_test_file("inst/tinytest/test_vi_firm.R") # Test with coverage covr::package_coverage() ``` -------------------------------- ### Example of Record-Style Object (POSIXlt) in R Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Demonstrates the behavior of a record-style object, POSIXlt, by showing its length and how its internal components can be accessed. It highlights that the user-facing length differs from the internal representation. ```R x <- as.POSIXlt(ISOdatetime(2020, 1, 1, 0, 0, 1:3)) length(x) unclass(x) x[[1]] unclass(x)[[1]] ``` -------------------------------- ### Create New Components in VIP Package Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Generates new R files, test files, vignettes, articles, or adds package dependencies using usethis functions. ```r # Create new R file usethis::use_r("file-name") # Create new test file (creates in inst/tinytest/) usethis::use_test("file-name") # Create vignette usethis::use_vignette("vignette-name") # Create article (website only) usethis::use_article("article-name") # Add package dependency usethis::use_package("packagename", type = "Imports") usethis::use_package("packagename", type = "Suggests") ``` -------------------------------- ### Create Helper Function for Percent Casting Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Provides an example of creating a user-friendly helper function `as_percent()` that leverages the defined `vec_cast` methods to simplify the conversion of various data types to the 'percent' class. ```r as_percent <- function(x) { vec_cast(x, new_percent()) } ``` -------------------------------- ### Running Tests with tinytest in R Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Commands to run tests within the vip R package using the tinytest framework. It shows how to execute a specific test file or the entire package test suite. ```r # Run specific tests tinytest::run_test_file("inst/tinytest/test_pkg_newmodel.R") # Run full suite tinytest::test_package("vip") ``` -------------------------------- ### TDD: Test New Model Support in VIP Package Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Demonstrates the Test-Driven Development process for adding new model support, including creating a test file, implementing the S3 method, updating documentation, and running tests. ```r # File: inst/tinytest/test_pkg_NEWMODEL.R exit_if_not(requireNamespace("NEWMODEL", quietly = TRUE)) # Load test data and fit model data("test_data") # or create synthetic data model <- NEWMODEL::fit_function(formula, data = test_data) # Define expectations expectations <- function(object) { expect_inherits(object, c("vi", "tbl_df", "tbl", "data.frame")) expect_equal(nrow(object), ncol(test_data) - 1L) expect_true(all(c("Variable", "Importance") %in% names(object))) } # Test vi_model method vi_result <- vi(model, method = "model") expectations(vi_result) # Test vip plotting p <- vip(model) expect_inherits(p, "ggplot") ``` ```r # File: R/vi_model.R #' @export vi_model.NEWMODEL <- function(object, type = NULL, ...) { # Extract variable importance imp <- NEWMODEL::importance_function(object, type = type) # Convert to standard tibble format tibble::tibble( Variable = names(imp), Importance = as.numeric(imp) ) } ``` ```r # Test new implementation tinytest::run_test_file("inst/tinytest/test_pkg_NEWMODEL.R") # Run full test suite tinytest::test_package("vip") ``` -------------------------------- ### Clone vip Repository and Setup Development Environment Source: https://github.com/koalaverse/vip/blob/main/README.md This bash script outlines the initial steps for setting up the development environment for the 'vip' R package. It includes cloning the repository from GitHub and navigating into the project directory. No specific dependencies are mentioned beyond standard git and shell access. ```bash # Clone the repo git clone https://github.com/koalaverse/vip.git cd vip # Open in RStudio or your favorite editor ``` -------------------------------- ### User-Friendly Rational Vector Constructor Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Provides a user-friendly constructor `rational` that simplifies the creation of rational vectors. It casts inputs to integers, recycles them to the same length, and then calls the low-level `new_rational` constructor. An example demonstrates its usage. ```R rational <- function(n = integer(), d = integer()) { c(n, d) %<-% vec_cast_common(n, d, .to = integer()) c(n, d) %<-% vec_recycle_common(n, d) new_rational(n, d) } x <- rational(1, 1:10) ``` -------------------------------- ### Roxygen2 Documentation Standard for Variable Importance Function Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Demonstrates the Roxygen2 documentation standard for the 'vi' function, which computes variable importance scores. It specifies parameters, return values, and includes an example of its usage with the randomForest package. This standard ensures consistent and informative documentation for R functions. ```r # Roxygen2 documentation standard #' Variable importance #' #' Compute variable importance scores for the predictors in a model. #' #' @param object A fitted model object #' @param method Character string specifying VI type ("model", "permute", "shap", "firm") #' @param feature_names Character vector of feature names to compute #' @param sort Logical indicating whether to sort results #' @param ... Additional arguments passed to specific methods #' #' @return A tibble with Variable and Importance columns #' #' @examples #' \dontrun{ #' library(randomForest) #' rf <- randomForest(Species ~ ., data = iris) #' vi_scores <- vi(rf) #' } #' #' @export vi <- function(object, ...) { UseMethod("vi") } ``` -------------------------------- ### Install vip R Package Source: https://github.com/koalaverse/vip/blob/main/README.md Installs the vip R package from CRAN for the stable version or the development version using pak for the latest features. This is the primary step to begin using the package's functionalities. ```r install.packages("vip") # Install development version (latest features) # install.packages("pak") pak::pak("koalaverse/vip") ``` -------------------------------- ### R Check Package with devtools Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Illustrates how to use `devtools::check()` in R to perform a comprehensive check of the package, simulating checks performed by CRAN. This command runs various tests, including code execution, documentation, and examples, to ensure package quality and stability. It's a critical step before package submission. The `cran = TRUE` argument ensures checks are performed with CRAN policies in mind. ```r # Check complete package (Ctrl/Cmd + Shift + E) devtools::check() # Check with CRAN settings devtools::check(cran = TRUE) ``` -------------------------------- ### R: Lossy Casting Example Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Demonstrates lossy casting in R using `vec_cast`. Shows a successful cast from a numeric vector to `integer` and an error generated when casting a `double` vector containing non-integer values to `integer`, indicating a loss of precision. ```R vec_cast(c(1, 2, 10), to = integer()) vec_cast(c(1.5, 2, 10.5), to = integer()) ``` -------------------------------- ### R User-Friendly Constructor for Percent Vector Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Implements and exports a user-friendly constructor function 'percent' for the 'pizza_percent' vector class. This function casts the input to double and uses the low-level constructor 'new_percent'. It includes roxygen2 documentation for help topics and examples. ```r #' `percent` vector #' #' This creates a double vector that represents percentages so when it is #' printed, it is multiplied by 100 and suffixed with `%`. #' #' @param x A numeric vector #' @return An S3 vector of class `pizza_percent`. #' @export #' @examples #' percent(c(0.25, 0.5, 0.75)) percent <- function(x = double()) { x <- vec_cast(x, double()) new_percent(x) } ``` -------------------------------- ### Code Quality Checks for VIP Package Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Utilizes linters and formatters to check code style and identify potential issues within the VIP package. ```r # Check code style lintr::lint_package() # Format code (if using styler) styler::style_pkg() # Check for potential issues goodpractice::gp() ``` -------------------------------- ### R Automatic devtools Loading in Rprofile Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Shows how to automatically load the 'devtools' package in R interactive sessions by adding a snippet to the user's `.Rprofile` file. This ensures that 'devtools' and its associated functionalities, including 'usethis', are readily available during development. It's a common practice for streamlining the R package development workflow. ```r # Add to ~/.Rprofile for automatic loading if (interactive()) { require("devtools", quietly = TRUE) # automatically attaches usethis } ``` -------------------------------- ### Implement Cached Sum Vector Math in R Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Shows an example of implementing the vec_math() generic for a 'cached_sum' class in R. It uses a switch statement to handle specific functions like 'sum' and 'mean', falling back to base R functions for others. ```r vec_math.vctrs_cached_sum <- function(.fn, .x, ...) { switch(.fn, sum = attr(.x, "sum"), mean = attr(.x, "sum") / length(.x), vec_math_base(.fn, .x, ...) ) } ``` -------------------------------- ### R Efficient Parallel Processing with foreach Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Demonstrates efficient parallel processing for permutation importance calculation using the 'foreach' package in R. It checks if parallel processing is enabled and registered, then uses '%dopar%' for parallel execution or '%do%' for sequential execution. This pattern optimizes performance for computationally intensive tasks. ```r # Efficient parallel processing with foreach vi_permute_parallel <- function(object, train, metric, nsim, parallel = FALSE, ...) { if (parallel && foreach::getDoParRegistered()) { results <- foreach::foreach(i = seq_len(nsim), .combine = rbind) %dopar% { compute_permutation_importance(object, train, metric) } } else { results <- foreach::foreach(i = seq_len(nsim), .combine = rbind) %do% { compute_permutation_importance(object, train, metric) } } results } ``` -------------------------------- ### Base R Recycling Warnings and Silent Recycling Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Illustrates scenarios in base R where vector recycling can lead to warnings, particularly when lengths are not compatible multiples. It also shows examples of functions that perform recycling silently without explicit warnings. ```r invisible(pmax(1:2, 1:3)) #> Warning in pmax(1:2, 1:3): an argument will be fractionally recycled invisible(1:2 + 1:3) #> Warning in 1:2 + 1:3: longer object length is not a multiple of shorter object #> length invisible(cbind(1:2, 1:3)) #> Warning in cbind(1:2, 1:3): number of rows of result is not a multiple of #> vector length (arg 1) length(atan2(1:3, 1:2)) #> [1] 3 length(paste(1:3, 1:2)) #> [1] 3 length(ifelse(1:3, 1:2, 1:2)) #> [1] 3 ``` -------------------------------- ### Demonstrating sapply Type and Size Instability in R Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/stability.html This example illustrates the type-unstable nature of sapply() in R, where the output type cannot be predicted solely from input types. It also demonstrates size-instability, particularly with matrices and data frames, where the output size may not directly correspond to the input size. ```r vec_ptype_show(sapply(1L, function(x) c(x, x))) #> Prototype: integer[,1] vec_ptype_show(sapply(integer(), function(x) c(x, x))) #> Prototype: list ``` -------------------------------- ### Testing Model-Specific VI and Plotting in R Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md A pattern for testing model-specific variable importance implementations in R. This function tests the basic `vi()` call, different importance methods ('permute', 'shap', 'firm'), and the `vip()` plotting function for a given model. ```r # Pattern for testing model-specific implementations test_model_vi <- function(model, expected_features) { # Test basic vi() call vi_result <- vi(model) expectations(vi_result, length(expected_features)) # Test with different methods for (method in c("model", "permute", "shap", "firm")) { if (supports_method(model, method)) { vi_method <- vi(model, method = method) expectations(vi_method, length(expected_features)) } } # Test vip() plotting p <- vip(model) expect_inherits(p, "ggplot") } ``` -------------------------------- ### Implementing S3 Method for New Model in R Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Implementation of an S3 method for a new model type ('newmodel') within the vip package. This function extracts variable importance scores from the fitted model object and formats them into a standard tibble structure. ```r # File: R/vi_model.R #' @export vi_model.newmodel <- function(object, ...) { # Extract importance scores importance <- newmodel::variable_importance(object) # Convert to standard format tibble::tibble( Variable = names(importance), Importance = as.numeric(importance) ) } ``` -------------------------------- ### R Rebuild Documentation and NAMESPACE with devtools Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Demonstrates the use of `devtools::document()` in R to rebuild package documentation and the NAMESPACE file. This function is essential for updating documentation comments (like Roxygen2) and managing package exports. It's a core command in the development cycle, often triggered by the RStudio shortcut Ctrl/Cmd + Shift + D. ```r # Rebuild docs and NAMESPACE (Ctrl/Cmd + Shift + D) devtools::document() ``` -------------------------------- ### R Check Documentation Spelling with devtools Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md Shows how to perform a spell check on package documentation using `devtools::spell_check()` in R. This command helps maintain the quality and professionalism of package documentation by identifying potential spelling errors. It's a useful step in the documentation and validation phase of the development workflow. ```r # Check documentation with spell check devtools::spell_check() ``` -------------------------------- ### Load MathJax Library Dynamically with JavaScript Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html This snippet demonstrates how to dynamically create and append a script tag to the document's head to load the MathJax library. It ensures that mathematical formulas are rendered correctly on the page. No external dependencies are required beyond a standard browser environment. ```javascript (function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"; document.getElementsByTagName("head")[0].appendChild(script); })(); ``` -------------------------------- ### Ensure Numeric Inputs for ww_local_geary_c Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_geary_c.md These examples show that the ww_local_geary_c function requires numeric inputs for both 'truth' and 'estimate' arguments. Providing non-numeric data will result in a specific error message. ```R ww_local_geary_c(worldclim_predicted, predicted, response) ``` ```R ww_local_geary_c(worldclim_predicted, response, predicted) ``` ```R ww_local_geary_c(worldclim_predicted, response, predicted) ``` ```R ww_local_geary_c(worldclim_predicted, predicted, response) ``` -------------------------------- ### ww_multi_scale: Successful execution with n=2 Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/multi_scale.md Shows a successful execution of the ww_multi_scale function with n set to 2. This example demonstrates the typical output format, a tibble containing performance metrics. ```r ww_multi_scale(worldclim_predicted, predicted, response, n = 2) ``` -------------------------------- ### Show Prototype of Matrices and Arrays (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Illustrates the output of `vec_ptype_show()` for matrices and arrays. The prototype includes the base type and dimensions, shown in a compact format. ```R vec_ptype_show(array(logical(), c(2, 3))) #> Prototype: logical[,3] vec_ptype_show(array(integer(), c(2, 3, 4))) #> Prototype: integer[,3,4] vec_ptype_show(array(character(), c(2, 3, 4, 5))) #> Prototype: character[,3,4,5] ``` -------------------------------- ### Get Prototype of Factor (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Shows how to retrieve the full prototype object for a factor using `vec_ptype()`, which includes the actual levels, unlike the hash shown by `vec_ptype_show()`. ```R vec_ptype(factor("a")) #> factor(0) #> Levels: a ``` -------------------------------- ### Handle Zero Non-Missing Values in ww_local_geary_c_vec Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_geary_c.md This example illustrates the error generated by ww_local_geary_c_vec when the 'truth' argument contains zero non-missing values. This typically happens when passing empty numeric vectors. ```R ww_local_geary_c_vec(numeric(), numeric(), structure(list(), class = "listw")) ``` -------------------------------- ### Handle Non-Numeric Truth in ww_global_geary_pvalue_vec (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_global_geary_pvalue.md Illustrates the error when the `truth` argument in `ww_global_geary_pvalue_vec` is not numeric. The code examples show the correct way to pass numeric data for the `truth` argument. ```R ww_global_geary_pvalue_vec(worldclim_predicted$predicted, worldclim_predicted$response, worldclim_weights) ``` -------------------------------- ### Implement Comparison Proxy for Decimal2 (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Shows how to implement `vec_proxy_compare` for the Decimal2 class. This proxy defines the ordering of Decimal2 objects, which is used by comparison operators like `<`, `<=`, `>=`, `>`, and functions like `min()`, `max()`, `median()`, and `quantile()`. ```R vec_proxy_compare.vctrs_decimal2 <- function(x, ...) { # Compare based on the combined value, considering the scale. # This typically involves converting to a common numeric type or comparing component-wise. val <- field(x, "l") + field(x, "r") / 10^attr(x, "scale") val } ``` -------------------------------- ### Create a double prototype Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Demonstrates creating a prototype for a double-precision floating-point vector using the base R double() function. Prototypes represent the metadata of a vector without any actual data. ```r double() ``` -------------------------------- ### Load R Libraries for vctrs and rlang Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/stability.html Loads the 'vctrs', 'rlang', and 'zeallot' libraries in R. These libraries are commonly used for advanced data manipulation, metaprogramming, and variable assignment, respectively. ```r library(vctrs) library(rlang) library(zeallot) ``` -------------------------------- ### Handle Non-Numeric Input for estimate in ww_local_moran_pvalue_vec (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_moran_pvalue.md This example shows the error when the 'estimate' argument provided to ww_local_moran_pvalue_vec is not numeric. The function expects numeric data for both 'truth' and 'estimate' to compute spatial autocorrelation. ```r ww_local_moran_pvalue_vec(worldclim_predicted$response, worldclim_predicted$predicted, worldclim_weights) ``` -------------------------------- ### Handle identical truth and estimate in ww_local_getis_ord_g_vec (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_getis_ord_g.md This example shows the output of ww_local_getis_ord_g_vec when the 'truth' and 'estimate' vectors are identical. In such cases, the function returns a vector of NaNs, indicating no variation or a trivial result. ```r ww_local_getis_ord_g_vec(worldclim_simulation$response, worldclim_simulation$ response, worldclim_weights) # Output # [1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [19] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [37] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [55] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [73] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ``` -------------------------------- ### Create a Custom 'percent' Vector Class Constructor Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Defines a low-level constructor `new_percent` for a custom 'percent' vector class. It ensures the input is a double vector and uses `new_vctr` to create the new vector with the specified class. This function is intended for internal use and type validation. ```r new_percent <- function(x = double()) { if (!is_double(x)) { abort("`x` must be a double vector.") } new_vctr(x, class = "vctrs_percent") } ``` -------------------------------- ### Create a new datetime prototype Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Demonstrates creating a prototype for a datetime vector using the vctrs helper function new_datetime(). This is particularly useful for handling timezones and other datetime-specific attributes. ```r new_datetime() ``` -------------------------------- ### Demonstrating ifelse() Type Instability in R Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/stability.html This example illustrates that ifelse() in R is type-unstable, as its output type depends on the values within the conditional vector. While it is length-stable, matching the length of the condition, its type can vary. ```r vec_ptype_show(ifelse(NA, 1L, 1L)) #> Prototype: logical vec_ptype_show(ifelse(FALSE, 1L, 1L)) #> Prototype: integer ``` -------------------------------- ### Decimal2 Vector User Constructor and Formatting (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Provides the user-facing `decimal2` constructor that casts inputs to integers, recycles them, and calls `new_decimal2`. It also includes the `format.vctrs_decimal2` method for displaying Decimal2 objects in a human-readable format, respecting the scale. ```R decimal2 <- function(l, r, scale = 2L) { l <- vec_cast(l, integer()) r <- vec_cast(r, integer()) c(l, r) %<-% vec_recycle_common(l, r) scale <- vec_cast(scale, integer()) # should check that r < 10^scale new_decimal2(l = l, r = r, scale = scale) } format.vctrs_decimal2 <- function(x, ...) { val <- field(x, "l") + field(x, "r") / 10^attr(x, "scale") sprintf(paste0("%.0", attr(x, "scale"), "f"), val) } ``` -------------------------------- ### R: Decimal Class Constructor and Formatting Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Implements the `decimal` class in R, including a low-level constructor `new_decimal` that takes data and a `digits` attribute, a user-friendly constructor `decimal`, a `digits` accessor, and a `format` method for printing decimals with a specified precision. ```R new_decimal <- function(x = double(), digits = 2L) { if (!is_double(x)) { abort("`x` must be a double vector.") } if (!is_integer(digits)) { abort("`digits` must be an integer vector.") } vec_check_size(digits, size = 1L) new_vctr(x, digits = digits, class = "vctrs_decimal") } decimal <- function(x = double(), digits = 2L) { x <- vec_cast(x, double()) digits <- vec_recycle(vec_cast(digits, integer()), 1L) new_decimal(x, digits = digits) } digits <- function(x) attr(x, "digits") format.vctrs_decimal <- function(x, ...) { sprintf(paste0("%-", 0, ".", digits(x), "f"), x) } ``` -------------------------------- ### Ensure Numeric Input for ww_global_geary_c Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_global_geary_c.md These examples demonstrate the requirement for numeric input for the `truth` and `estimate` arguments in the `ww_global_geary_c` function. Providing non-numeric data, such as character strings or factors, will result in an error from the `ww_global_geary_c` function. ```R ww_global_geary_c(worldclim_predicted, predicted, response) ``` ```R ww_global_geary_c(worldclim_predicted, response, predicted) ``` -------------------------------- ### Handle Identical Inputs in ww_local_moran_pvalue_vec (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_moran_pvalue.md This example demonstrates the output when both 'truth' and 'estimate' arguments in ww_local_moran_pvalue_vec are identical and contain valid data. In such cases, the function returns a vector of NaNs, indicating no spatial autocorrelation can be detected. ```r ww_local_moran_pvalue_vec(worldclim_simulation$response, worldclim_simulation$response, worldclim_weights) ``` -------------------------------- ### Implement Equality Proxy for Decimal2 (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Demonstrates the implementation of `vec_proxy_equal` for the Decimal2 class. This function returns a data vector suitable for comparison, underpinning operations like `==`, `!=`, `unique()`, and `is.na()`. ```R vec_proxy_equal.vctrs_decimal2 <- function(x, ...) { # Default behavior calls vec_proxy(), which returns the raw data. # For Decimal2, this means returning a list of 'l' and 'r' fields. list(l = field(x, "l"), r = field(x, "r")) } ``` -------------------------------- ### Fix Length Mismatch in ww_local_moran_i_vec (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_moran_i.md This snippet addresses errors where the length of 'truth' and 'estimate' vectors do not match when using ww_local_moran_i_vec. It shows examples of how to adjust the input vectors to ensure they have the same length, which is a requirement for the function to execute correctly. ```R ww_local_moran_i_vec(worldclim_predicted$response, tail(worldclim_predicted$ predicted, -1), worldclim_weights) ``` ```R ww_local_moran_i_vec(tail(worldclim_predicted$response, -1), worldclim_predicted$predicted, worldclim_weights) ``` -------------------------------- ### Create a Rational Vector Constructor Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Defines a low-level constructor `new_rational` for creating rational vectors. It takes named integer vectors for the numerator and denominator and creates a new record (rcrd) of class 'vctrs_rational'. Input validation ensures that `n` and `d` are integer vectors. ```R new_rational <- function(n = integer(), d = integer()) { if (!is_integer(n)) { abort("`n` must be an integer vector.") } if (!is_integer(d)) { abort("`d` must be an integer vector.") } new_rcrd(list(n = n, d = d), class = "vctrs_rational") } ``` -------------------------------- ### Expected NaN output from ww_local_geary_pvalue_vec with identical inputs Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_geary_pvalue.md This example shows the output of `ww_local_geary_pvalue_vec` when both the 'response' and 'predicted' arguments are identical. In such cases, the function returns `NaN` (Not a Number) for all calculations, indicating that the spatial autocorrelation cannot be meaningfully computed under these conditions. ```r ww_local_geary_pvalue_vec(worldclim_simulation$response, worldclim_simulation$response, worldclim_weights) # Output # [1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [19] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [37] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [55] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN # [73] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ``` -------------------------------- ### Handle Missing Values in spatial_yardstick_vec (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_local_moran_pvalue.md This example shows the error that occurs when missing values are present in the input data for spatial_yardstick_vec, a function used by ww_local_moran_pvalue_vec. The waywiser package requires complete data when spatial weights are applied. ```r ww_local_moran_pvalue_vec(worldclim_predicted$predicted, worldclim_predicted$response, worldclim_weights) ``` ```r ww_local_moran_pvalue_vec(worldclim_predicted$response, worldclim_predicted$predicted, worldclim_weights) ``` ```r ww_local_moran_pvalue_vec(NA_real_, NA_real_, structure(list(neighbours = 1), class = "listw")) ``` -------------------------------- ### Percent Class Interaction with Base R `c()` Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Explains the behavior of the 'percent' class when used with the base R `c()` function, highlighting cases where it works correctly and where it may lead to errors due to type coercion limitations in base R. ```r # Correct c(percent(0.5), 1) #> [1] 0.5 1.0 c(percent(0.5), factor(1)) #> Error in `vec_c()`: #> ! Can't combine `..1` and `..2` >. # Incorrect c(factor(1), percent(0.5)) #> [1] 1.0 0.5 ``` -------------------------------- ### Create a new date prototype Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Shows how to create a prototype for a date vector using the vctrs helper function new_date(). This is useful when base R equivalents are insufficient for representing specific date-related metadata. ```r new_date() ``` -------------------------------- ### Handle NA and NaN with na_rm = TRUE in ww_unsystematic_agreement_coefficient Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_unsystematic_agreement_coefficient.md When the `na_rm` argument is set to TRUE (the default behavior), the ww_unsystematic_agreement_coefficient function and its vector version will ignore NA and NaN values in both 'truth' and 'estimate'. This example shows the calculation proceeds and returns an estimate. ```R round(ww_unsystematic_agreement_coefficient(missing_df, x, y)$.estimate, 15) # [1] 1 ``` ```R round(ww_unsystematic_agreement_coefficient(missing_df, y, x)$.estimate, 15) # [1] 1 ``` ```R round(ww_unsystematic_agreement_coefficient_vec(missing_df$y, missing_df$x), 15) # [1] 1 ``` ```R round(ww_unsystematic_agreement_coefficient_vec(missing_df$x, missing_df$y), 15) # [1] 1 ``` -------------------------------- ### Create Decimal2 Vector Constructor (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Defines the `new_decimal2` constructor for the Decimal2 class, which stores decimal values as a pair of integers (left and right of the decimal point) and a scale. It includes input validation to ensure components are integers and checks the scale size. ```R new_decimal2 <- function(l, r, scale = 2L) { if (!is_integer(l)) { abort("`l` must be an integer vector.") } if (!is_integer(r)) { abort("`r` must be an integer vector.") } if (!is_integer(scale)) { abort("`scale` must be an integer vector.") } vec_check_size(scale, size = 1L) new_rcrd(list(l = l, r = r), scale = scale, class = "vctrs_decimal2") } ``` -------------------------------- ### Implement Percent Class Casting with `vec_cast` Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Shows how to implement casting methods for the 'percent' class to convert between 'percent' and 'double' types. This allows explicit conversion of data when needed, ensuring data integrity and expected behavior. ```r vec_cast.vctrs_percent.vctrs_percent <- function(x, to, ...) x vec_cast.vctrs_percent.double <- function(x, to, ...) percent(x) vec_cast.double.vctrs_percent <- function(x, to, ...) vec_data(x) vec_cast(0.5, percent()) #> #> [1] 50% vec_cast(percent(0.5), double()) #> [1] 0.5 ``` -------------------------------- ### Standardized VI Object Validation in R Source: https://github.com/koalaverse/vip/blob/main/CLAUDE.md A helper function in R for validating the structure and content of variable importance (VI) objects generated by the vip package. It checks the class, dimensions, column names, and data types of the importance scores. ```r # Standard expectation function for VI objects expectations <- function(object, n_features) { # Check class expect_identical(class(object), target = c("vi", "tbl_df", "tbl", "data.frame")) # Check dimensions expect_identical(n_features, target = nrow(object)) # Check required columns expect_true(all(c("Variable", "Importance") %in% names(object))) # Check for valid importance scores expect_true(all(is.numeric(object$Importance))) expect_true(all(is.finite(object$Importance))) } ``` -------------------------------- ### Implement Order Proxy for Decimal2 (R) Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Illustrates the implementation of `vec_proxy_order` for the Decimal2 class. This proxy is used for sorting vectors and is typically called by `xtfrm()`, which in turn is used by `order()` and `sort()`. ```R vec_proxy_order.vctrs_decimal2 <- function(x, ...) { # For Decimal2, the order is the same as the comparison. # The default implementation calls vec_proxy_compare(), which is suitable here. vec_proxy_compare(x, ...) } ``` -------------------------------- ### Create a User-Friendly 'percent' Vector Class Constructor Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/s3-vector.html Provides a user-friendly constructor `percent` for the 'percent' vector class. It utilizes `vec_cast` to ensure the input can be coerced to a double vector before calling the low-level `new_percent` constructor. This function is designed for general user interaction and handles type coercion. ```r percent <- function(x = double()) { x <- vec_cast(x, double()) new_percent(x) } ``` -------------------------------- ### R: Handle unsupported metric in vi_permute Source: https://github.com/koalaverse/vip/blob/main/revdep/problems.md This R code snippet demonstrates an error encountered during the execution of examples in 'waywiser-Ex.R'. The error arises from an unsupported metric 'rsquared' being used in the `vi_permute` function. It suggests using `vip::list_metrics()` or a `yardstick` vector function. ```R train <- gen_friedman(1000, seed = 101) test <- train[701:1000, ] train <- train[1:700, ] pp <- stats::ppr(y ~ ., data = train, nterms = 11) importance <- vi_permute(pp, target = "y", metric = "rsquared", pred_wrapper = predict) Error: Metric "rsquared" is not supported; use `vip::list_metrics()` to print a list of currently supported metrics. Alternatively, you can pass in a `yardstick` vector function directly (e.g., `metric = yardstick::poisson_log_loss_vec` (just be sure to also set the `smaller_is_better` argument. Execution halted ``` -------------------------------- ### Show Common Prototype of Matrices and Arrays in R Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html This code snippet demonstrates how `vec_ptype_show()` handles matrices and arrays. It shows how arrays are broadcast to higher dimensions and the errors that can occur when dimensions are incompatible. The output shows the intermediate steps of the coercion process. ```R vec_ptype_show( array(1, c(0, 1)), array(1, c(0, 2)) ) #> Prototype: #> 0. ( , ) = #> 1. ( , ) = vec_ptype_show( array(1, c(0, 1)), array(1, c(0, 3)), array(1, c(0, 3, 4)), array(1, c(0, 3, 4, 5)) ) #> Prototype: #> 0. ( , ) = #> 1. ( , ) = #> 2. ( , ) = #> 3. ( , ) = vec_ptype_show( array(1, c(0, 2)), array(1, c(0, 3)) ) #> Error: #> ! Can't combine `out_types[[i - 1]]` and `in_types[[i]]` . #> ✖ Incompatible sizes 2 and 3 along axis 2. ``` -------------------------------- ### Create a new duration prototype Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Illustrates creating a prototype for a duration vector using the vctrs helper function new_duration(). This allows for precise representation of time intervals. ```r new_duration() ``` -------------------------------- ### Error: Invalid `na_rm` Argument in ww_multi_scale Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/multi_scale.md This example demonstrates an error condition where the `na_rm` argument is provided with multiple logical values, while the function expects only a single logical value. This typically occurs when trying to specify different NA handling strategies simultaneously. ```R ww_multi_scale(suppressWarnings(sf::st_centroid(guerry_modeled)), Crm_prs, predictions, n = list(c(1, 1)), na_rm = c(TRUE, FALSE), metrics = yardstick::rmse) ``` -------------------------------- ### Create a factor prototype Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Illustrates creating a prototype for a factor vector with specified levels using the base R factor() function. This prototype captures the levels attribute, which is crucial for factor operations. ```r factor(levels = c("a", "b")) ``` -------------------------------- ### Allowing Lossy Casts Source: https://github.com/koalaverse/vip/blob/main/revdep/library.noindex/vip/new/vctrs/doc/type-size.html Demonstrates the use of allow_lossy_cast to suppress errors that occur during casting when information might be lost. It can be used generally or with specific prototypes to control the casting behavior. ```R allow_lossy_cast( vec_cast(c(1.5, 2), integer()) ) #> [1] 1 2 allow_lossy_cast( vec_cast(c(1.5, 2), integer()), x_ptype = double(), to_ptype = integer() ) #> [1] 1 2 ``` -------------------------------- ### Handle NA and NaN with na_rm = TRUE in ww_systematic_rmpd Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/srr-ww_systematic_rmpd.md When `na_rm` is set to `TRUE` (which is the default behavior for `ww_systematic_rmpd`), NA and NaN values in `truth` and `estimate` are ignored during calculation. This example demonstrates that the function correctly computes an estimate of 0 when only NA/NaN values are present after removal. ```R round(ww_systematic_rmpd(missing_df, x, y)$.estimate, 15) ``` ```R round(ww_systematic_rmpd(missing_df, y, x)$.estimate, 15) ``` ```R round(ww_systematic_rmpd_vec(missing_df$y, missing_df$x), 15) ``` ```R round(ww_systematic_rmpd_vec(missing_df$x, missing_df$y), 15) ``` -------------------------------- ### Basic Usage of ww_multi_scale with sf Object Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/multi_scale.md Demonstrates the fundamental usage of the ww_multi_scale function with an sf object, specifying the target variable, predictions, and a subset of grids. It outputs a tibble with performance metrics. ```R ww_multi_scale(ames_sf, Sale_Price, predictions, grids = grids[1], metrics = yardstick::rmse) ``` -------------------------------- ### Build Spatial Weights with ww_build_weights Source: https://github.com/koalaverse/vip/blob/main/revdep/checks.noindex/waywiser/new/waywiser.Rcheck/tests/testthat/_snaps/misc_yardstick.md Demonstrates how to use the `ww_build_weights` function to create a spatial weights list object (`listw`). This is a fundamental step for many spatial analysis functions in the waywiser package. The output is a tibble containing metric, estimator, and estimate values. ```r df_local_i <- ww_local_getis_ord_g(guerry_modeled, Crm_prs, predictions, wt = ww_build_weights) df_local_i[1:3] ``` -------------------------------- ### Advanced: Permutation Importance with Custom Metrics in R Source: https://github.com/koalaverse/vip/blob/main/README.md Illustrates how to calculate permutation-based variable importance using a custom metric (RMSE) and enhanced plotting options. This example uses the ranger package for model fitting and highlights parallel processing for speed. ```r library(ranger) # Fit model rf_model <- ranger(mpg ~ ., data = mtcars, importance = "none") # Permutation importance with custom metric vi_perm <- vi( rf_model, method = "permute", train = mtcars, target = "mpg", metric = "rmse", nsim = 50, # 50 permutations for stability parallel = TRUE # Speed up with parallel processing ) # Create enhanced plot vip(vi_perm, num_features = 10, geom = "point") + labs(title = "Permutation-based Variable Importance", subtitle = "RMSE metric, 50 permutations") + theme_minimal() ``` -------------------------------- ### Quick Start: Generate Variable Importance Plot in R Source: https://github.com/koalaverse/vip/blob/main/README.md Demonstrates the basic usage of the vip package. It involves fitting a randomForest model to the iris dataset, extracting importance scores using the vi() function, and then visualizing these scores with the vip() function. ```r library(vip) library(randomForest) # Fit a model model <- randomForest(Species ~ ., data = iris) # Get importance scores vi_scores <- vi(model) print(vi_scores) # Create a beautiful plot vip(model) ```