Skip to contents

Applies a user-defined function to each row (when rows are active) or each column (when columns are active), providing both the values and the opposite dimension's metadata. This enables complex statistical modeling where you need access to all annotations.

Usage

compute_across(
  .data,
  fn,
  add_to_data = FALSE,
  prefix = NULL,
  return_tibble = TRUE,
  ...
)

Arguments

.data

A tidymatrix object with rows or columns active (not matrix)

fn

A function with signature function(values, metadata, ...) where:

  • values: Numeric vector of row/column values

  • metadata: Complete col_data (rows active) or row_data (columns active)

  • ...: Additional arguments from compute_across() Must return a named list or named vector

add_to_data

Logical. If TRUE, adds results to row_data/col_data and returns modified tidymatrix. If FALSE (default), returns data.frame

prefix

Character. Optional prefix for result column names when add_to_data = TRUE

return_tibble

Logical. If TRUE (default), returns tibble. If FALSE, returns data.frame. Only applies when add_to_data = FALSE

...

Additional arguments passed to fn

Value

If add_to_data = FALSE: data.frame/tibble with one row per matrix row/column, containing identifiers and computed statistics. If add_to_data = TRUE: modified tidymatrix with results added to metadata.

Examples

# T-test example
mat <- matrix(rnorm(100, mean = 10), nrow = 10, ncol = 10)
col_data <- data.frame(
  sample = paste0("S", 1:10),
  condition = rep(c("Control", "Treatment"), each = 5)
)
row_data <- data.frame(gene = paste0("Gene", 1:10))
tm <- tidymatrix(mat, row_data, col_data)

# Run t-test on each row
results <- tm |>
  activate(rows) |>
  compute_across(
    fn = function(vals, meta) {
      test <- t.test(vals ~ meta$condition)
      list(
        p.value = test$p.value,
        log2fc = log2(mean(vals[meta$condition == "Treatment"]) /
                      mean(vals[meta$condition == "Control"]))
      )
    }
  )

# Linear model with multiple predictors
col_data2 <- data.frame(
  sample = paste0("S", 1:10),
  condition = rep(c("Control", "Treatment"), each = 5),
  batch = factor(rep(1:2, 5)),
  age = rnorm(10, 50, 10)
)
tm2 <- tidymatrix(mat, row_data, col_data2)

lm_results <- tm2 |>
  activate(rows) |>
  compute_across(
    fn = function(vals, meta) {
      fit <- lm(vals ~ condition + batch + age, data = meta)
      summ <- summary(fit)
      coef_summ <- coef(summ)

      list(
        condition_pval = coef_summ["conditionTreatment", "Pr(>|t|)"],
        condition_coef = coef_summ["conditionTreatment", "Estimate"],
        r.squared = summ$r.squared
      )
    }
  )

# Add results to metadata
tm_with_stats <- tm |>
  activate(rows) |>
  compute_across(
    fn = function(vals, meta) {
      test <- t.test(vals ~ meta$condition)
      list(p.value = test$p.value)
    },
    add_to_data = TRUE,
    prefix = "ttest"
  )