Maintainer: Sebastian Krantz (sebastian.krantz@graduateinstitute.ch)
collapse hex sticker
collapse is a large C/C++-based infrastructure package facilitating complex statistical computing, data transformation, and exploration tasks in R - at outstanding levels of performance and memory efficiency. It also implements a class-agnostic approach to R programming supporting vector, matrix and data frame-like objects (including xts, tibble, data.table, and sf). It has a stable API, depends on Rcpp, and supports R versions >= 3.4.0.
Relationship with data.table
At the C-level, collapse took much inspiration from data.table, and leverages some of its core algorithms like radixsort, while adding significant statistical functionality and new algorithms within a class-agnostic programming framework that seamlessly supports data.table. Notably, collapse::qDT() is a highly efficient anything to data.table converter, and all manipulation functions in collapse return a valid data.table object when a data.table is passed, enabling subsequent reference operations (:=).
Or simply, convenience functions like collap() for fast multi-type aggregation:
# World Development Dataset (see ?wlddev)head(wlddev, 3)
country iso3c date year decade region income OECD PCGDP LIFEEX GINI ODA POP
1 Afghanistan AFG 1961-01-01 1960 1960 South Asia Low income FALSE NA 32.446 NA 116769997 8996973
2 Afghanistan AFG 1962-01-01 1961 1960 South Asia Low income FALSE NA 32.962 NA 232080002 9169410
3 Afghanistan AFG 1963-01-01 1962 1960 South Asia Low income FALSE NA 33.471 NA 112839996 9351441
# Population weighted mean for numeric and mode for non-numeric columns (multithreaded and # vectorized across groups and columns, the default in statistical functions is na.rm = TRUE)wlddev |>collap(~ year + income, fmean, fmode, w =~ POP, nthreads =4) |>ss(1:3)
country iso3c date year decade region income OECD PCGDP LIFEEX GINI
1 United States USA 1961-01-01 1960 1960 Europe & Central Asia High income TRUE 12768.7126 68.59372 NA
2 Ethiopia ETH 1961-01-01 1960 1960 Sub-Saharan Africa Low income FALSE 658.4778 38.33382 NA
3 India IND 1961-01-01 1960 1960 South Asia Lower middle income FALSE 500.7932 45.26707 NA
ODA POP
1 911825661 749495030
2 160457982 147355735
3 3278899549 927990163
We can also use the low-level API for statistical programming:
vars <-c("carb", "hp", "qsec") # columns to aggregate# Aggregating: weighted mean - vectorized across groups and columns add_vars(g$groups, # Grouping columnsfmean(get_vars(mtcars, vars), g, w = mtcars$wt, use.g.names =FALSE))
# Multiply the rows with a vector (by reference)setop(m, "*", mtcars$mpg, rowwise =TRUE)# Replace some elements with a numbersetv(m, 3:40, 5.76) # Could also use a vector to copy fromwhichv(m, 5.76) # get the indices back...
It is also fairly easy to do more involved data exploration and manipulation:
# Groningen Growth and Development Center 10 Sector Database (see ?GGDC10S)namlab(GGDC10S, N =TRUE, Ndistinct =TRUE, class =TRUE)
Variable Class N Ndist Label
1 Country character 5027 43 Country
2 Regioncode character 5027 6 Region code
3 Region character 5027 6 Region
4 Variable character 5027 2 Variable
5 Year numeric 5027 67 Year
6 AGR numeric 4364 4353 Agriculture
7 MIN numeric 4355 4224 Mining
8 MAN numeric 4355 4353 Manufacturing
9 PU numeric 4354 4237 Utilities
10 CON numeric 4355 4339 Construction
11 WRT numeric 4355 4344 Trade, restaurants and hotels
12 TRA numeric 4355 4334 Transport, storage and communication
13 FIRE numeric 4355 4349 Finance, insurance, real estate and business services
14 GOV numeric 3482 3470 Government services
15 OTH numeric 4248 4238 Community, social and personal services
16 SUM numeric 4364 4364 Summation of sector GDP
# Describe total Employment and Value-Addeddescr(GGDC10S, SUM ~ Variable)
Dataset: GGDC10S, 1 Variables, N = 5027
Grouped by: Variable [2]
N Perc
EMP 2516 50.05
VA 2511 49.95
------------------------------------------------------------------------------------------------------------------------
SUM (numeric): Summation of sector GDP
Statistics (N = 4364, 13.19% NAs)
N Perc Ndist Mean SD Min Max Skew Kurt
EMP 2225 50.99 2225 36846.87 96318.65 173.88 764200 5.02 30.98
VA 2139 49.01 2139 43'961639.1 358'350627 0 8.06794210e+09 15.77 289.46
Quantiles
1% 5% 10% 25% 50% 75% 90% 95% 99%
EMP 256.12 599.38 1599.27 3555.62 9593.98 24801.5 66975.01 152402.28 550909.6
VA 0 25.01 444.54 21302 243186.47 1'396139.11 15'926968.3 104'405351 692'993893
------------------------------------------------------------------------------------------------------------------------
# Compute growth rate (Employment and VA, all sectors)GGDC10S_growth <-tfmv(GGDC10S, AGR:SUM, fgrowth, # tfmv = transform variables. Alternatively: fmutate(across(...))g =list(Country, Variable), t = Year, # Internal grouping and ordering, passed to fgrowth()apply =FALSE) # apply = FALSE ensures we call fgrowth.data.frame# Recast the dataset, median growth rate across years, taking along variable labels GGDC_med_growth <-pivot(GGDC10S_growth,ids =c("Country", "Regioncode", "Region"),values =slt(GGDC10S, AGR:SUM, return ="names"), # slt = shorthand for fselect()names =list(from ="Variable", to ="Sectorcode"),labels =list(to ="Sector"), FUN = fmedian, # Fast function = vectorizedhow ="recast"# Recast (transposition) method) |>qDT()GGDC_med_growth[1:3]
Country Regioncode Region Sectorcode Sector VA EMP
<char> <char> <char> <fctr> <fctr> <num> <num>
1: BWA SSA Sub-saharan Africa AGR Agriculture 8.790267 0.8921475
2: ETH SSA Sub-saharan Africa AGR Agriculture 6.664964 2.5876142
3: GHA SSA Sub-saharan Africa AGR Agriculture 28.215905 1.4045550
# Finally, lets just join this to wlddev, enabling multiple matches (cartesian product)# -> on average 61 years x 11 sectors = 671 records per unique (country) matchjoin(wlddev, GGDC_med_growth, on =c("iso3c"="Country"), how ="inner", multiple =TRUE) |>ss(1:3)
country iso3c date year decade region income OECD PCGDP LIFEEX GINI
1 Argentina ARG 1961-01-01 1960 1960 Latin America & Caribbean Upper middle income FALSE 5642.765 65.055 NA
2 Argentina ARG 1961-01-01 1960 1960 Latin America & Caribbean Upper middle income FALSE 5642.765 65.055 NA
3 Argentina ARG 1961-01-01 1960 1960 Latin America & Caribbean Upper middle income FALSE 5642.765 65.055 NA
ODA POP Regioncode Region Sectorcode Sector VA EMP
1 219809998 20481779 LAM Latin America AGR Agriculture 32.91968 -0.8646301
2 219809998 20481779 LAM Latin America MIN Mining 25.72799 1.5627293
3 219809998 20481779 LAM Latin America MAN Manufacturing 26.66754 1.0801500
In summary:collapse provides flexible high-performance statistical and data manipulation tools, which extend and seamlessly integrate with data.table. The package follows a similar development philosophy emphasizing API stability, parsimonious syntax, and zero dependencies (apart from Rcpp). data.table users may wish to employ collapse for some of the advanced statistical and manipulation functionality showcased above, but also to efficiently manipulate other data frame-like objects, such as sf data frames.