Skip to contents

ordinal_matrix_to_factor() converts a weighted ordinal-count response matrix into a factor response and row weights. It is the inverse of the ordinal-count response representation returned by design_data() and design_newdata() when response_type = "ordinal_counts".

Use this helper when a model, metric, or diagnostic needs a factor response plus case weights rather than a count matrix.

Usage

ordinal_matrix_to_factor(y)

Arguments

y

(numeric matrix)
Ordinal-count response matrix. Rows are observations and columns are ordinal response levels.

Value

A list with elements:

  • y: a factor with levels = colnames(y).

  • weights: a numeric vector equal to rowSums(y).

The returned factor and weights are aligned row-for-row with the input matrix.

Details

The matrix column names define the factor levels. Column order is preserved as the factor's level order. Column names must be non-missing, non-empty, and unique.

Values must be non-missing, finite, and non-negative. Each row must have either zero positive cells or exactly one positive cell. Rows with one positive cell return that column as the factor level and the row's positive cell value as its weight. Rows with all zeros return NA and weight 0. Rows with more than one positive cell error.

The function does not require integer counts. Fractional values are allowed because design-generated ordinal-count matrices use analysis weights.

Examples

#----------------------------------------------------------------------------
# Convert a weighted ordinal-count matrix
#----------------------------------------------------------------------------
library(bkmodel)

counts <- matrix(
  c(0, 1.2, 0,
    0.8, 0, 0,
    0, 0, 1.5,
    0, 0, 0),
  ncol = 3L,
  byrow = TRUE,
  dimnames = list(NULL, c("low", "medium", "high"))
)

converted <- ordinal_matrix_to_factor(counts)
converted$y
#> [1] medium low    high   <NA>  
#> Levels: low medium high
converted$weights
#> [1] 1.2 0.8 1.5 0.0

#----------------------------------------------------------------------------
# Round-trip from design_data(response_type = "ordinal_counts")
#----------------------------------------------------------------------------
set.seed(1L)
analysis <- data.frame(
  response = ordered(
    c("low", "medium", "high", "low", "medium", "high"),
    levels = c("low", "medium", "high")
  ),
  marker = c(0.2, 0.4, 1.1, 0.3, 0.8, 1.4),
  sampling_weight = c(1.0, 0.5, 1.5, 1.2, 0.8, 1.1)
)

spec <- design_spec(
  response ~ marker,
  weights = ~ sampling_weight
)

fit <- design_fit(spec, analysis)
ordinal_inputs <- design_data(
  fit,
  response_type = "ordinal_counts"
)

factor_inputs <- ordinal_matrix_to_factor(ordinal_inputs$y)
factor_inputs$y
#> [1] low    medium high   low    medium high  
#> Levels: low medium high
factor_inputs$weights
#> [1] 1.0 0.5 1.5 1.2 0.8 1.1