Skip to main content
v2026.11,858 entries · CC-BY 4.0

Collapse in R: collapse(), fct_collapse() and paste()

Collapse in R means four things: paste(collapse=), forcats::fct_collapse(), dplyr::collapse() and the collapse package. Syntax and examples from the docs.

Written and maintained by CASRAI Editorial Board

Last updated

“Collapse” means four different things in R, and searches for collapse in R land on all of them: the collapse package for fast data transformation, dplyr::collapse() for database queries, forcats::fct_collapse() for merging factor levels, and the collapse argument of paste() for joining a vector into one string. This guide separates the four, shows the documented syntax for each, and gives a worked recoding example for survey-style categorical data.

Which “collapse” do you need?

You want to Use Where it comes from
Join the elements of a character vector into a single string paste(x, collapse = ", ") Base R
Merge several factor levels into fewer, manually defined groups forcats::fct_collapse() forcats (tidyverse)
Force a lazy database query to generate its SQL without running it dplyr::collapse() dplyr (tidyverse)
Do fast grouped and weighted statistics on large data The collapse package CRAN

What it is used for in research

In research data work the two most common senses are recoding and reporting. fct_collapse() reduces a survey or coding variable with many response categories to the few groups an analysis plan actually uses, for example combining “No answer” and “Don’t know” into a single missing group. paste(..., collapse = ) turns a vector of values (author names, identifiers, variable names) into one string for a table cell or a log line. The collapse package targets large datasets: its CRAN description is “A large C/C++-based package for advanced data transformation and statistical computing in R”, with grouped and weighted statistical functions and fast grouping and ordering. The database sense, dplyr::collapse(), matters when your data lives in a SQL database rather than in memory. Collapsing categories is a recoding decision, so record it in your analysis plan or data-cleaning log; the data cleaning steps guide covers how to document such changes.

Install or access

All four senses come from official sources on CRAN or the tidyverse sites.

  • paste(): part of base R, nothing to install.
  • The collapse package: listed on CRAN as “collapse: Advanced and Fast Data Transformation” (version 2.1.8, published 2026-08-30, as checked on 2026-10-29), licensed GPL (>= 2). Install it from CRAN with install.packages("collapse") and load it with library(collapse).
  • dplyr::collapse(): part of the dplyr package; documented on the dplyr reference page “Force computation of a database query”.
  • forcats::fct_collapse(): part of the forcats package; documented on the forcats reference page “Collapse factor levels into manually defined groups”.

Step-by-step: collapse factor levels with fct_collapse()

The documented usage is fct_collapse(.f, ..., other_level = NULL, group_other = "DEPRECATED"). You give it a factor and one named argument per new group, each set to the old levels it should absorb. The forcats reference example recodes the party-identification variable partyid in the gss_cat survey data:

  1. Load the package: library(forcats).
  2. Pass the factor as .f.
  3. Name each new group and list the old levels it replaces:
    partyid2 <- fct_collapse(gss_cat$partyid,
      missing = c("No answer", "Don't know"),
      other   = "Other party",
      rep     = c("Strong republican", "Not str republican"),
      ind     = c("Ind,near rep", "Independent", "Ind,near dem"),
      dem     = c("Not str democrat", "Strong democrat"))
  4. Check the result with a frequency count, for example table(partyid2).

The other_level argument sets the name of the level used for “other” values, and the documentation states it is always placed at the end of the levels. The group_other argument is deprecated.

Step-by-step: collapse a vector into one string with paste()

The documented usage is paste (..., sep = " ", collapse = NULL, recycle0 = FALSE). The R manual describes collapse as “an optional character string to separate the results” and states: “When collapse is a string, the result is always a string (character of length 1).” Its own example, “To collapse the output into a single string, pass a collapse argument”, uses paste0(nth, collapse = ", "). Note the difference from sep: sep separates the arguments element by element, while collapse joins the finished results into one string.

Step-by-step: compute(), collect() and collapse() in dplyr

The three functions share one reference page, with usage compute(x, ...), collect(x, ...) and collapse(x, ...). The documentation defines them in one line each:

Function What the dplyr documentation says
compute() Stores results in a remote temporary table.
collect() Retrieves data into a local tibble.
collapse() “Doesn’t force computation, but instead forces generation of the SQL query.”

All three preserve grouping and ordering, and x can be a data frame, tibble or lazy data frame (from dbplyr or dtplyr). The reference example uses an in-memory SQLite database holding mtcars, filtered to cyl == 8. collect() on that query returns a tibble of 14 rows by 5 columns, while collapse() returns another lazy query and prints Source: SQL [?? x 5] with the row count shown as unknown.

The collapse package

The CRAN page for collapse lists its categories as grouped and weighted statistical functions, fast grouping and ordering, and data object conversions. Use library(collapse) after installing, then follow the package documentation linked from the CRAN page (the package website at fastverse.org/collapse and the PDF manual) for individual function signatures. This guide does not reproduce them. For the base-R and tidyverse ways to describe a variable by group, see the CASRAI guides on the interquartile range in R and crosstabs in R.

Output and how to read it

  • paste(collapse = ) returns a character vector of length 1. If you leave collapse = NULL, you get a vector the same length as the longest input.
  • fct_collapse() returns a factor with fewer levels. In the forcats example the 10 levels of partyid become 5, with counts of missing 155, other 393, rep 5346, ind 8409 and dem 7180. Always compare those counts against the original table: the group totals should add up to the original row count.
  • dplyr::collapse() returns a lazy query, not data. Nothing is pulled into R until you call collect().

Before and after recoding, plot or tabulate the variable to see what you merged; see histograms in R and box plots in R for numeric variables, and the CASRAI dictionary entry on types of variables for when a variable should be treated as categorical.

Troubleshooting

  • You expected one string but got a vector. The collapse argument of paste() defaults to NULL; set it to a string such as ", ".
  • Your merged group got a different label than expected. In fct_collapse() the argument name becomes the new level name; the levels you list must match the original level text exactly, including punctuation.
  • Two packages provide a function called collapse. If you loaded both the collapse package and dplyr, R may report that one masks the other; call the function with its package prefix, for example dplyr::collapse().
  • You want to pull database results into R. Use collect(), which returns a local tibble.

Related functions and free alternatives

These are the functions the official documentation presents for the same jobs. All are available from CRAN or base R.

Job Function Documented behaviour
Join values into one string paste() / paste0() with collapse Result is a character vector of length 1 when collapse is a string
Merge factor levels by hand forcats::fct_collapse() Unspecified “other” values go to other_level, placed last
Keep a database query lazy but generate SQL dplyr::collapse() Forces generation of the SQL query without computing it
Store a query result in a temporary database table dplyr::compute() Stores results in a remote temporary table
Bring query results into R dplyr::collect() Retrieves data into a local tibble
Fast grouped and weighted statistics The collapse package GPL (>= 2) licensed C/C++-based package on CRAN

FAQ

Is collapse in R a function or a package?

Both, and more. collapse is a CRAN package, dplyr::collapse() is a function in dplyr, and collapse is also an argument of paste(). forcats::fct_collapse() is the separate function for factor levels.

How do I collapse a character vector into a single string in R?

Pass a string to the collapse argument: paste0(x, collapse = ", "). The manual states the result is then always a string of length 1.

How do I combine factor levels in R?

Use forcats::fct_collapse() with one named argument per new group, as in the gss_cat$partyid example above.

What is the difference between collapse(), compute() and collect() in dplyr?

collapse() forces generation of the SQL query without computing it, compute() stores results in a remote temporary table, and collect() retrieves data into a local tibble.

Sources (official documentation, checked 2026-10-29)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Collapse in R: collapse(), fct_collapse() and paste()

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Ask CASRAI · Regulatory Radar

Research-admin question? Get an answer that links its sources.

An AI assistant specialized in research administration. Every answer links its sources to check before you act. 2 questions free, no account. $29/month after.

  • Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.
  • Every answer numbers its sources and links each one, so you can check the source yourself.