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

Summarize Function in R: Syntax, Grouping, and Examples

Learn how to use the summarize function in R (dplyr::summarise) to aggregate datasets, calculate group statistics, and apply vectorized functions.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

The summarize function in R (spelled interchangeably as summarize() or summarise() in the dplyr package) aggregates a data frame or tibble into a compact summary table by evaluating user-specified statistical summary expressions. When applied to an ungrouped dataset, it calculates summary statistics across entire columns and returns a single row. When paired with grouping variables—either via the group_by() verb or through the per-operation .by argument—it executes the split-apply-combine workflow, computing separate aggregate values for each distinct subgroup and returning one row per group. Researchers rely on summarize() to calculate essential descriptive metrics, including sample counts, arithmetic means, medians, standard deviations, and quantiles, while preserving clean, reproducible data manipulation pipelines across scientific workflows.

What it is used for in research

In empirical research, experimental measurements and clinical trial records rarely arrive pre-aggregated. Analysts must condense micro-level patient visits, sensor readings, or survey responses into group-level descriptive metrics before fitting regression models or plotting figures. The summarize() function in R’s dplyr package serves as the standard computational tool for this aggregation task across modern scientific workflows.

Quantitative investigations depend on summarize() for several core methodological objectives:

  • Cohort and demographic profiling: Clinical trials and epidemiologic studies require baseline participant tables (Table 1). Researchers use summarize() to compute central tendencies and dispersion metrics—such as mean age, median biomarker concentrations, and interquartile ranges—stratified by intervention cohort.
  • Longitudinal data aggregation: In studies involving wearable telemetry, repeated assays, or multi-timepoint surveys, raw observations are collapsed into subject-level daily averages or baseline-to-endpoint changes before fitting mixed-effects models.
  • Sample tracking and protocol adherence: Methodological transparency demands reporting exact observation counts. Pairing summarize() with n() (total rows) and n_distinct() (unique subject identifiers) verifies participant retention and reveals subgroup attrition.
  • Monitoring missing data patterns: In observational research, data missingness threatens valid inference. Combining summarize() with logical expressions such as sum(is.na(variable)) quantifies missingness across experimental conditions prior to imputation or sensitivity analyses.

A key strength of summarize() is its adherence to tidy data principles. Unlike console tools that emit formatted text summaries, summarize() returns a rectangular tibble where every column is a variable and every row corresponds to a group. This structural consistency ensures outputs feed directly into downstream visualization and reporting pipelines.

How to install or access it

The summarize() function is maintained within the open-source dplyr package, curated by the Posit team and hosted on The Comprehensive R Archive Network (CRAN). CRAN provides verified binaries and source packages for Linux, macOS, and Windows under the permissive MIT license.

To install dplyr directly from CRAN, execute the following command in an interactive R terminal or script:

install.packages("dplyr")

Alternatively, researchers utilizing the broader Tidyverse suite (including ggplot2, tidyr, readr, and tibble) can install the complete bundle from CRAN:

install.packages("tidyverse")

Official package specifications on CRAN confirm that dplyr release 1.2.1 requires R version 4.1.0 or higher. The package depends on core infrastructure libraries including rlang, vctrs, tibble, tidyselect, and cli. To access the function in an active R session, load the library:

library(dplyr)

Comprehensive reference documentation, changelogs, and official vignettes are published on the official Tidyverse documentation portal at https://dplyr.tidyverse.org/reference/summarise.html and mirrored on CRAN.

Step-by-step instructions

The following step-by-step task demonstrates how to execute descriptive summaries on a representative clinical trial cohort dataset evaluating systolic blood pressure (SBP), baseline biomarker concentrations, and visit compliance across study arms.

  1. Step 1: Initialize session and load required libraries

    Load the dplyr package to register its data-masking verbs in the global namespace:

    library(dplyr)
  2. Step 2: Construct the illustrative research dataset

    Instantiate a reproducible patient cohort tibble containing treatment arm assignments, study sites, SBP readings, and laboratory biomarker measurements:

    set.seed(42)
    trial_data <- tibble(
      patient_id   = paste0("PT-", 101:120),
      study_arm    = rep(c("Placebo", "Low Dose", "High Dose", "Standard Care"), each = 5),
      site_id      = rep(c("Site_A", "Site_B"), times = 10),
      sbp_baseline = c(142, 138, 145, NA, 150, 136, 140, 134, 139, 144,
                       155, 148, 152, 160, 147, 130, 135, 128, 132, 140),
      sbp_week12   = c(140, 139, 144, 146, 148, 128, 130, 126, 131, 135,
                       138, 132, 135, 141, 130, 125, 128, 122, 127, 134),
      biomarker_mg = c(4.2, 5.1, 3.8, 6.0, 4.9, 5.5, 6.2, 4.8, 5.0, 5.7,
                       7.1, 6.8, 8.0, 7.5, 6.9, 3.9, 4.1, 3.5, 4.0, 4.3)
    )
  3. Step 3: Execute an ungrouped dataset-wide summary

    When passed an ungrouped tibble, summarize() returns one row summarizing the entire study population. Explicitly set na.rm = TRUE within vector aggregation functions to account for missing clinical observations:

    global_summary %
      summarize(
        total_enrolled   = n(),
        valid_sbp_cases  = sum(!is.na(sbp_baseline)),
        missing_sbp      = sum(is.na(sbp_baseline)),
        mean_sbp_base    = mean(sbp_baseline, na.rm = TRUE),
        sd_sbp_base      = sd(sbp_baseline, na.rm = TRUE),
        median_biomarker = median(biomarker_mg, na.rm = TRUE),
        iqr_biomarker    = IQR(biomarker_mg, na.rm = TRUE)
      )
    
    print(global_summary)
  4. Step 4: Compute group-specific summaries using the transient .by argument

    In dplyr 1.1.0+, perform grouped operations using the .by argument directly inside summarize(). This approach implements per-operation grouping and automatically returns an ungrouped tibble, avoiding lingering grouped states in memory:

    arm_summary %
      summarize(
        n_patients      = n(),
        mean_baseline   = mean(sbp_baseline, na.rm = TRUE),
        mean_week12     = mean(sbp_week12, na.rm = TRUE),
        mean_reduction  = mean(sbp_baseline - sbp_week12, na.rm = TRUE),
        sd_reduction    = sd(sbp_baseline - sbp_week12, na.rm = TRUE),
        .by = study_arm
      )
    
    print(arm_summary)
  5. Step 5: Execute multi-level grouping with group_by() and manage .groups

    When performing nested comparisons across multiple categorical factors, pair summarize() with group_by(). Always supply the .groups argument to govern the grouping structure of the resulting tibble:

    nested_summary %
      group_by(study_arm, site_id) %>%
      summarize(
        sample_size     = n(),
        mean_sbp_post   = mean(sbp_week12, na.rm = TRUE),
        sd_sbp_post     = sd(sbp_week12, na.rm = TRUE),
        .groups         = "drop"
      )
    
    print(nested_summary)

    Setting .groups = "drop" ensures that the output is a completely ungrouped tibble, preventing accidental group-based filtering or mutation bugs in downstream scripts.

  6. Step 6: Aggregate multiple variables simultaneously using across()

    Use the across() verb inside summarize() to vectorize functions across selected columns using tidyselect semantics and format column names via the .names parameter:

    multi_metric_summary %
      summarize(
        n_subjects = n(),
        across(
          .cols = c(sbp_baseline, sbp_week12, biomarker_mg),
          .fns  = list(
            mean = ~ mean(.x, na.rm = TRUE),
            sd   = ~ sd(.x, na.rm = TRUE)
          ),
          .names = "{.col}_{.fn}"
        ),
        .by = study_arm
      )
    
    print(multi_metric_summary)
  7. Step 7: Pipe summarized tibbles into downstream reporting and verification

    Because the resulting summary table maintains a clean tabular structure, researchers can seamlessly feed the output into custom validation functions using R’s define function conventions, export results to CSV files via readr::write_csv(), or render formatted tables for manuscripts using packages such as knitr::kable().

Output and how to read it

When summarize() completes execution, it produces an object belonging to class c("tbl_df", "tbl", "data.frame"), commonly called a tibble.

When printed to the R console, the output displays three distinct informational layers:

  1. Header and dimensional metadata: The first line indicates object dimensions (e.g., # A tibble: 4 x 6), signifying 4 rows (representing 4 treatment arms) and 6 columns (the grouping variable plus 5 summary statistics). If the tibble retained grouping metadata, a second line such as # Groups: study_arm [4] indicates the active grouping hierarchy.
  2. Column names and data types: Each variable name is accompanied by an abbreviated data type label directly beneath the header. Common labels include [chr] for character grouping factors, [int] for integer counts generated by n(), and [dbl] for double-precision floating-point metrics produced by mean() or sd().
  3. Rectangular data matrix: Below metadata headers, individual rows display calculated values. If a subgroup contains exclusively missing values and na.rm = TRUE was specified, functions like mean() output NaN, whereas min() or max() emit Inf or -Inf accompanied by a base R warning.

It is important to contrast the structured tabular output of summarize() with base R’s exploratory summary function in R. Base R’s summary() returns a named table or print-oriented summary object displaying six-number summaries (Min, 1st Qu., Median, Mean, 3rd Qu., Max). While valuable for interactive terminal exploration, base summary() does not yield a tidy rectangular data frame suitable for automated filtering or joining. In contrast, dplyr::summarize() provides programmatic control over variable names and formulas.

Troubleshooting

When developing data preparation scripts, researchers encounter specific runtime errors. Below are the primary failure modes encountered when using summarize() and their verified remedies:

1. Column must be length 1 (a summary value), not 2 or more

Symptom: The R interpreter halts with an error: Error in summarize(): ! In argument: mean_val = quantile(sbp_baseline, probs = c(0.25, 0.75)). Caused by error: ! Column 'mean_val' must be length 1 (a summary value), not 2.

Cause: By definition, classical summarize() expressions expect functions that reduce a vector down to a single scalar value. Passing an expression that yields multiple values (such as range() or quantile() with multiple probabilities) violates this constraint.

Resolution: To extract individual quantiles within summarize(), evaluate single probability points separately (e.g., q25 = quantile(x, 0.25, na.rm = TRUE), q75 = quantile(x, 0.75, na.rm = TRUE)). Alternatively, if multi-row output per group is deliberately intended, utilize dplyr::reframe(), which was introduced in dplyr 1.1.0 to handle multiple rows per group without triggering errors.

2. Calculations return NA across all summary rows

Symptom: Summary columns for mean, sd, or var evaluate to NA for one or more groups, even though the raw data contains dozens of valid numerical observations.

Cause: In base R, arithmetic aggregation functions (including mean(), sum(), sd(), var(), and median()) default to na.rm = FALSE. Under this strict mathematical behavior, if even one observation in a subgroup is missing (NA), the entire aggregate evaluates to NA to prevent silent omission of unobserved data.

Resolution: If protocol allows complete-case evaluation for that endpoint, explicitly add na.rm = TRUE to the aggregation call: mean(sbp_baseline, na.rm = TRUE). In parallel, compute sum(is.na(sbp_baseline)) within the same summarize() block so that peer reviewers and collaborators can assess the extent of missingness.

3. Masking conflicts between dplyr and plyr or Hmisc

Symptom: Calling summarize() unexpectedly produces an error such as Error in summarize_impl(.data, dots): ..., ignores group_by() structure, or returns a standard data frame with corrupted column structures.

Cause: Loading legacy packages such as plyr, Hmisc, or MASS after loading dplyr causes their homonymous summarize functions to mask dplyr::summarize() in the R search path.

Resolution: Use explicit package namespacing by writing dplyr::summarize() in production scripts. Alternatively, ensure package load order places library(dplyr) or library(tidyverse) after legacy packages, or use the conflicted package to enforce explicit namespace disambiguation across your environment.

4. Console message: summarise() has grouped output by ‘variable’

Symptom: R displays an informative console message: `summarise()` has grouped output by 'study_arm'. You can override using the `.groups` argument.

Cause: When summarize() operates on a tibble grouped by two or more variables, its default behavior (the historical "drop_last" mode) drops the innermost grouping level while retaining outer grouping levels. R emits this message to remind the analyst that the resulting tibble remains partially grouped.

Resolution: Prevent ambiguity by explicitly defining the desired output structure via the .groups argument: specify .groups = "drop" to strip all grouping hierarchies, .groups = "drop_last" to retain outer groups silently without console messages, or use the modern .by argument for transient grouping.

Free alternatives

While dplyr::summarize() is the predominant aggregation tool in tidy data analysis, researchers have access to several free, open-source alternatives within the R language ecosystem. The appropriate tool depends on dataset volume, dependency constraints, and pipeline architecture.

The comparative table below outlines the primary free alternatives available in base R and CRAN packages for executing group summaries:

Tool / Function Package / Ecosystem Primary Syntax Pattern Grouping Mechanism Memory and Performance Model License
dplyr::summarize() dplyr (Tidyverse) summarize(df, m = mean(x), .by = g) .by or group_by() In-memory C++ (vctrs); out-of-core via dbplyr / DuckDB MIT
base::aggregate() stats (Base R) aggregate(x ~ g, data = df, FUN = mean) Formula interface or list of factors In-memory base R; slower on high-cardinality groups GPL-2 | GPL-3
base::tapply() base (Base R) tapply(df$x, df$g, FUN = mean) Factor or list of factors In-memory array / ragged vector evaluation GPL-2 | GPL-3
base::summary() base (Base R) summary(df) or summary(model) No grouping; operates on full object In-memory exploratory summary table GPL-2 | GPL-3
data.table data.table (CRAN) DT[, .(m = mean(x)), by = g] by = .(g) or keyby In-memory C-optimized fast radsort aggregation MPL-2.0
duckdb (SQL) duckdb (CRAN / Engine) dbGetQuery(con, "SELECT g, AVG(x) FROM t GROUP BY g") SQL GROUP BY Vectorized out-of-core query engine; exceeds RAM capacity MIT
Rmisc::summarySE() Rmisc (CRAN) summarySE(df, measurevar = "x", groupvars = "g") Vector of character column names In-memory wrapper calculating mean, SD, SE, and 95% CI GPL-3

For scripts intended for base R distribution where zero third-party dependencies are allowed, aggregate() provides a robust formula syntax, although it requires separate calls for multi-variable aggregations with different summary functions. When processing massive datasets exceeding millions of records, data.table delivers superior computational speed and minimal memory overhead through in-place evaluations. Similarly, researchers analyzing biological sequencing or health records larger than workstation RAM can leverage duckdb, which pairs directly with dplyr syntax via dbplyr to translate summarize() calls directly into optimized SQL execution plans. For standard publication reporting where standard error and confidence intervals are required alongside group means, researchers can compare specialized helpers such as summarySE in R.

The structured data table below compares these aggregation engines across execution models, syntax complexity, dependency weight, and high-cardinality performance benchmarks.

Frequently asked questions

What is the difference between summarize and summarise in R?

There is no functional or performance difference between summarize() and summarise() in R. Both names are exported synonyms within the dplyr package. The dual naming exists to accommodate both American English (summarize) and British or Commonwealth English (summarise) spelling conventions. You can use either form interchangeably without altering the returned tibble, grouping behavior, or calculation results.

How does summarize differ from the base R summary function?

While their names appear related, dplyr::summarize() and base::summary() serve completely different purposes. The base R summary() function is an exploratory generic function that prints a standard 6-number summary (Min, 1st Quartile, Median, Mean, 3rd Quartile, Max) for numeric vectors or model coefficient tables for regression objects. It does not easily produce customizable grouped tables. In contrast, dplyr::summarize() is a data manipulation verb that applies user-defined mathematical functions across groups and returns a tidy, rectangular data frame ready for downstream analysis.

Why does summarize return NA for mean or standard deviation calculations?

Calculations evaluate to NA because base R statistical functions like mean(), sd(), median(), and var() default to na.rm = FALSE. Under this default, if a single observation within a group contains an NA value, R preserves mathematical rigor by returning NA. To compute statistics across observed values while excluding missing entries, supply na.rm = TRUE inside the summary function, such as mean(sbp_baseline, na.rm = TRUE).

What does the .groups argument do in summarize?

The .groups argument controls the grouping metadata of the data frame returned by summarize(). When summarizing data grouped by multiple variables, the default setting ("drop_last") removes the innermost grouping variable while retaining outer grouping levels. Setting .groups = "drop" drops all grouping structures and yields an ungrouped tibble. Setting .groups = "keep" preserves the original grouping structure, and .groups = "rowwise" converts each output row into an individual group.

When should researchers use .by instead of group_by?

Researchers should use the .by argument (e.g., summarize(df, mean_val = mean(x), .by = cohort)) when performing one-off summary calculations that do not require persistent grouping downstream. The .by argument was introduced in dplyr 1.1.0 to provide per-operation grouping. It always returns an ungrouped tibble, eliminating the common bug where analysts forget to call ungroup() after group_by(), which can inadvertently corrupt subsequent filtering or mutating operations.

How do you summarize multiple columns simultaneously in R?

To summarize multiple columns simultaneously without repetitive code, use the across() helper function inside summarize(). By specifying column selection rules (such as across(where(is.numeric), mean, na.rm = TRUE) or across(c(sbp, dbp, heart_rate), list(mean = mean, sd = sd))), you can apply multiple summary functions across dozens of variables in a single vectorized statement. Use the .names argument to format resulting column headers systematically.

What is the difference between summarize and reframe in dplyr?

In dplyr 1.1.0 and later versions, summarize() is strictly designated for expressions that return a single summary value (length 1) per group. If a user-supplied expression returns multiple rows per group (for example, generating a 5-point summary with quantile()), summarize() emits a warning or error. The reframe() verb was introduced specifically to handle multi-row outputs per group, making the analyst’s intention explicit and preventing accidental row multiplication in summary pipelines.

Sources

  • R Core Team. The Comprehensive R Archive Network (CRAN): Package dplyr (Version 1.2.1). Published 2026-04-03. Accessed 2026-11-16. https://cran.r-project.org/web/packages/dplyr/index.html
  • Wickham, H., François, R., Henry, L., Müller, K., and Vaughan, D. dplyr: A Grammar of Data Manipulation (Reference Documentation: summarise). Tidyverse / Posit Software. Accessed 2026-11-16. https://dplyr.tidyverse.org/reference/summarise.html
  • Wickham, H. and Vaughan, D. Apply a Function across Multiple Columns (Reference Documentation: across). Tidyverse / Posit Software. Accessed 2026-11-16. https://dplyr.tidyverse.org/reference/across.html
  • R Core Team. R: Object Summaries (base::summary). ETH Zürich R-Manual Documentation. Accessed 2026-11-16. https://stat.ethz.ch/R-manual/R-devel/library/base/html/summary.html
  • R Core Team. R: Compute Summary Statistics of Data Subsets (stats::aggregate). ETH Zürich R-Manual Documentation. Accessed 2026-11-16. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/aggregate.html
  • Dowle, M. and Srinivasan, A. Package data.table: Extension of ‘data.frame’. CRAN Archive. Accessed 2026-11-16. https://cran.r-project.org/web/packages/data.table/index.html

Data: Comparison of Summary Aggregation Engines in R Statistical Computing

Comparative technical evaluation of primary summary and aggregation functions in R, analyzing package origin, syntax paradigm, grouping mechanisms, multi-row support, memory constraints, and high-cardinality group scalability based on CRAN and base R documentation.

Comparison of Summary Aggregation Engines in R Statistical Computing
Engine / FunctionPackage EcosystemCRAN LicenseGrouping MechanismTransient Grouping (.by)Multi-Column VectorizationMulti-Row Output HandlingOut-of-Core DB Support
dplyr::summarize()TidyverseMIT.by argument or group_by()Supported (.by in dplyr 1.1+)across() helper functionEnforces length 1; reframe() for >1Supported via dbplyr and DuckDB
base::aggregate()Base R (stats)GPL-2 | GPL-3Formula (y ~ x) or list of factorsNot supported (persistent formula/list)cbind() in formula or multi-column data frameConverts matrix outputs to multi-column cellsNot supported natively
base::tapply()Base R (base)GPL-2 | GPL-3INDEX factor or list of factorsNot supported (evaluated per call)Requires iterative apply or loopReturns 1D array or list of vectorsNot supported natively
data.table [ , .(..), by ]data.table (CRAN)MPL-2.0by = .(var) or keybyNative per-query by clause.SD and .SDcols with lapply()Native recycling and row expansionIn-memory only; DuckDB integration
duckdb (SQL GROUP BY)DuckDB / DBIMITSQL GROUP BY clauseNative per-query SQL groupingSQL aggregate list or column enumerationAggregates return 1 row per groupNative vectorized out-of-core disk engine
Rmisc::summarySE()Rmisc (CRAN)GPL-3groupvars character vectorNot supported (wrapper function)Single measurevar per callReturns single summary row per groupNot supported natively

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

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

Ask CASRAI · free to try

Ask about Summarize Function in R: Syntax, Grouping, and Examples

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

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 open 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 →