Skip to contents

Aggregate grouped rows or columns, applying summary functions to metadata and aggregating the matrix. For numeric matrices, the default aggregation is mean(). For non-numeric matrices, you must specify .matrix_fn.

Usage

# S3 method for class 'grouped_tidymatrix'
summarize(.data, ..., .matrix_fn = NULL, .matrix_args = list(), .groups = NULL)

# S3 method for class 'grouped_tidymatrix'
summarise(.data, ..., .matrix_fn = NULL, .matrix_args = list(), .groups = NULL)

Arguments

.data

A grouped_tidymatrix object

...

Name-value pairs of summary functions for metadata

.matrix_fn

Function to aggregate matrix values within each group. Default is mean for numeric matrices. Required for non-numeric matrices.

.matrix_args

List of additional arguments to pass to .matrix_fn (e.g., list(na.rm = TRUE))

.groups

Grouping structure of result (same as dplyr::summarize)

Value

An ungrouped tidymatrix object with aggregated data. Stored analysis objects are removed (with a warning), because they describe the data before aggregation; metadata columns are kept.

Examples

library(dplyr, warn.conflicts = FALSE)
mat <- matrix(rnorm(20), nrow = 10, ncol = 2)
row_data <- data.frame(
  id = 1:10,
  group = rep(c("A", "B"), each = 5)
)
tm <- tidymatrix(mat, row_data)

# Summarize with default (mean) for numeric matrix
tm |>
  activate(rows) |>
  group_by(group) |>
  summarize(n = n(), avg_id = mean(id))
#> # A tidymatrix: 2 x 2 matrix
#> # Active: rows
#> #
#> # Row data: 2 rows x 3 columns
#> # Column data: 2 rows x 1 columns
#> #
#> # Active data (rows):
#>   group n avg_id
#> 1     A 5      3
#> 2     B 5      8

# Use different aggregation function
tm |>
  activate(rows) |>
  group_by(group) |>
  summarize(n = n(), .matrix_fn = median)
#> # A tidymatrix: 2 x 2 matrix
#> # Active: rows
#> #
#> # Row data: 2 rows x 2 columns
#> # Column data: 2 rows x 1 columns
#> #
#> # Active data (rows):
#>   group n
#> 1     A 5
#> 2     B 5

# With additional arguments
mat_na <- mat
mat_na[1, 1] <- NA
tm_na <- tidymatrix(mat_na, row_data)
tm_na |>
  activate(rows) |>
  group_by(group) |>
  summarize(n = n(), .matrix_fn = mean, .matrix_args = list(na.rm = TRUE))
#> # A tidymatrix: 2 x 2 matrix
#> # Active: rows
#> #
#> # Row data: 2 rows x 2 columns
#> # Column data: 2 rows x 1 columns
#> #
#> # Active data (rows):
#>   group n
#> 1     A 5
#> 2     B 5