Count the number of observations in each group, aggregating the matrix. Returns a tidymatrix (not a tibble).
Arguments
- x
A tidymatrix object
- ...
Variables to group by
- wt
Frequency weights (not yet implemented)
- sort
If TRUE, sort output in descending order of n
- name
Name of count column (default: "n")
- .drop
Drop groups with zero observations
- .matrix_fn
Function to aggregate matrix values. Default is
meanfor numeric matrices. Required for non-numeric matrices.- .matrix_args
List of additional arguments to pass to
.matrix_fn
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),
subgroup = rep(c("x", "y"), 5)
)
tm <- tidymatrix(mat, row_data)
# Count by single variable
tm |>
activate(rows) |>
count(group)
#> # 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
# Count by multiple variables
tm |>
activate(rows) |>
count(group, subgroup)
#> # A tidymatrix: 4 x 2 matrix
#> # Active: rows
#> #
#> # Row data: 4 rows x 3 columns
#> # Column data: 2 rows x 1 columns
#> #
#> # Active data (rows):
#> group subgroup n
#> 1 A x 3
#> 2 A y 2
#> 3 B x 2
#> 4 B y 3
# Use different aggregation for matrix
tm |>
activate(rows) |>
count(group, .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