collapse

repository·master·Indexed 20 days ago

https://github.com/fastverse/collapse

A high-performance R package written in C/C++ for advanced data transformation, statistical computing, and time-series/panel data analysis. It features a class-agnostic architecture supporting standard R objects and extensions like data.table, tibble, and xts. Key capabilities include fast grouped and weighted computations, multi-type aggregation, high-speed pivoting and joining, and specialized operators for panel data lags and differences.

Tokens
12K
Snippets
53
Records
56
Agent score
71%

What's inside collapse

  1. Overview of collapse

    master

    collapse is a high-performance C/C++-based R package designed for fast data transformation and statistical computing. It is optimized for complex tasks including grouped/weighted computations, data aggregation, and time-series/panel data manipulation.

    Key Capabilities:

    • Advanced Statistical Programming: Fast functions for grouped and weighted computations on vectors, matrices, and data frames; efficient grouping, ordering, and factor generation.
    • Fast Data Manipulation: Efficient data object conversions and memory-optimized R programming.
    • Advanced Aggregation & Transformations: Multi-type, weighted, and parallelized aggregation; fast row/column arithmetic and (grouped) sweeping/scaling.
    • Time-Series & Panel Data: Specialized support for indexed time series and panel data, including lags, leads, differences, and growth rates.
    • List Processing: Recursive searching, filtering, and splitting of lists.
    • Data Exploration: Fast descriptive statistical tools supporting grouped and weighted data.

    Architecture: It uses a class-agnostic architecture that supports standard R objects and popular extensions like units, integer64, xts/zoo, tibble, grouped_df, data.table, sf, pseries, and pdata.frame.

  2. Perform high-performance grouping and aggregation with collapse

    master

    The collapse package provides highly optimized functions for data manipulation, particularly when working with a large number of groups. For many common operations, collapse outperforms dplyr, data.table, and arrow (when using unordered grouping).

    Key patterns for high performance:

    • Use fgroup_by(..., sort = FALSE) to avoid the overhead of sorting groups when order is not required.
    • Use fselect() to subset columns before performing aggregations.
    • Use specialized aggregation functions like fsum(), fmean(), fmedian(), fsd() (standard deviation), and fndistinct() (number of distinct values).
    # Example: Fast aggregation across many groups
    taxi |> 
      fgroup_by(vendor_id, pickup_location_id, passenger_count, sort = FALSE) |> 
      fselect(total_amount, fare_amount, tip_amount) |> 
      fsum()
  3. Create and use indexed series with findex_by()

    master

    Indexing allows you to treat data as a collection of time series. Use findex_by() to create an indexed object. Once indexed, you can perform time-series operations like G() (growth) or psmat() (convert to panel matrix) directly on the object, and the operations will respect the index structure.

    # Create an indexed object
    exportsi <- exports |> findex_by(c, s, y)
    
    # Perform operations on the indexed object
    exportsi |> G(0:1) |> head(5)
    
    # Convert to a panel matrix
    exportsi$v |> psmat() |> head(3)
    
    # Check if the series is irregular
    is_irregular(exportsi$v)
  4. Use advanced window and transformation functions in collapse

    master

    collapse supports advanced operations that are often slow or unsupported in other frameworks like arrow. These include:

    • Cumulative operations: fcumsum() for cumulative sums.
    • Centering and Scaling: fwithin() for centering data within groups, fscale() for scaling, and settransform() to apply these to the original data frame.
    • Weighted statistics: fmean() and fmedian() support weighted calculations using the keep.w argument.
    • Growth and Rolling stats: fgrowth() for growth rates and frollmean() for rolling averages.
    • Regression: Perform linear regression within groups using fwithin() and fsummarise() to calculate slopes.
    # Example: Weighted mean within groups
    taxi |> 
      fgroup_by(vendor_id, pickup_location_id, dropoff_location_id, passenger_count, sort = FALSE) |> 
      fselect(total_amount, trip_distance) |> 
      fmean(trip_distance, keep.w = FALSE, na.rm = FALSE)
    
    # Example: Rolling average
    taxi[, rollavg := frollmean(total_amount, 10), by = .(vendor_id, pickup_location_id, dropoff_location_id, passenger_count)]
  5. Access collapse documentation and resources

    master

    The package includes several ways to learn and reference its functionality:

    • Built-in Structured Documentation: Access the top-level overview and links to all other documentation pages by calling help('collapse-documentation') in R.
    • Vignettes: Detailed guides are available, including a specific vignette on Documentation and Resources.
    • Cheatsheet: A visual reference guide is available as a PDF.
    • JSS Article: For academic reference, see the article published in the Journal of Statistical Software.
  6. Install collapse

    master

    You can install collapse via CRAN, R-universe (for development binaries), or GitHub.

    Install current version from CRAN

    Use the standard install.packages command.

    Install stable development version (Windows/Mac binaries)

    Use the R-universe repository to get binaries without local compilation.

    Install stable development version from GitHub

    Requires local compilation. Use the remotes package.

    Install previous versions from CRAN Archive

    Requires local compilation. Provide the direct URL to the source tarball.

    # Install the current version on CRAN
    install.packages("collapse")
    
    # Install a stable development version (Windows/Mac binaries) from R-universe
    install.packages("collapse", repos = "https://fastverse.r-universe.dev")
    
    # Install a stable development version from GitHub (requires compilation)
    remotes::install_github("fastverse/collapse")
    
    # Install previous versions from the CRAN Archive (requires compilation)
    install.packages("https://cran.r-project.org/src/contrib/Archive/collapse/collapse_2.0.19.tar.gz", 
                     repos = NULL, type = "source") 
  7. Manipulate data using fast verbs and pipes

    master

    You can use collapse functions within a pipe workflow (e.g., using magrittr or dplyr). While dplyr verbs work, collapse specific verbs are significantly faster.

    Key Manipulation Functions

    • fgroup_by(data, ...): Efficiently creates a grouped tibble.
    • fsubset(data, condition, grouping, selection): Fast selecting and subsetting.
    • add_vars(data, ...): Adds new variables (like weights) to a dataset.
    • fvar(data, w): Frequency-weighted group variance.
    • roworder(data, ...): Reorders rows.
    • fndistinct(data, g): Grouped distinct value counts.

    Example Workflow

    library(magrittr)
    iris %>%
      fgroup_by(Species) %>%
      fndistinct
    
    # Complex pipeline
    iris %>%
      add_vars(w) %>%
      fsubset(Sepal.Length < fmean(Sepal.Length), Species, Sepal.Width:w) %>%
      fgroup_by(Species) %>%
      fvar(w) %>%
      roworder(sum.w)
    library(magrittr)
    iris %>%
      fgroup_by(Species) %>%
      fndistinct
    
    iris %>%
      add_vars(w) %>%
      fsubset(Sepal.Length < fmean(Sepal.Length), Species, Sepal.Width:w) %>%
      fgroup_by(Species) %>%
      fvar(w) %>%
      roworder(sum.w)
  8. Configure collapse global settings with set_collapse()

    master

    Use set_collapse() to configure global execution parameters for the collapse package. This includes controlling how missing values are handled, whether results are sorted, and the number of threads used for parallel processing.

    Common parameters:

    • na.rm: Boolean indicating whether to remove NA values during computation.
    • sort: Boolean indicating whether to sort the output.
    • nthreads: Integer specifying the number of threads for parallel execution.
    set_collapse(na.rm = FALSE, sort = FALSE, nthreads = 4)
  9. Reshape data using the pivot() function

    master

    The pivot() function allows for high-speed reshaping of data between long and wide formats, serving as an alternative to tidyr::pivot_longer and tidyr::pivot_wider.

    Pivot Long

    To convert data from wide to long format:

    # collapse equivalent of tidyr::pivot_longer
    pivot(flights, values = vars)

    Pivot Wide

    To convert data from long to wide format, use the how argument:

    • how = "wider": Standard wide reshaping.
    • FUN: A function to apply to values if multiple values exist for a cell (e.g., fsum or "sum").
    # Example: Pivot wide with a summary function
    pivot(flights, .c(month, day, dest), vars, "origin", how = "wider", FUN = fsum)
    pivot(flights, values = vars)