R/table.to.vectors.R

Defines functions table.to.vectors

Documented in table.to.vectors

# Author: Xuye Luo
# Date: December 11, 2025

#' @title Recover Raw Data Vectors from Contingency Table
#'
#' @description Converts a contingency table (count data) back into two vectors of raw observations. 
#' This is useful when you have a summary table but need to run tests that require 
#' raw data vectors (like the functions in this package).
#'
#' @param x A numeric matrix or contingency table containing non-negative integer counts. 
#'          Must not contain NA values.
#' @return A list containing two integer vectors:
#' \item{x_vector}{A vector of row indices corresponding to the observations.}
#' \item{y_vector}{A vector of column indices corresponding to the observations.}
#' @export
#'
#' @examples
#' library("Upsilon")
#' 
#' # Create a sample contingency table
#' # Rows = Variable A (levels 1,2), Cols = Variable B (levels 1,2,3)
#' tab <- matrix(c(10, 5, 2, 8, 5, 10), nrow = 2, byrow = TRUE)
#' print(tab)
#' 
#' # Recover the raw vectors
#' res <- table.to.vectors(tab)
#' 
#' # Check the result
#' length(res$x_vector) # Should be sum(tab) = 40
#' head(cbind(res$x_vector, res$y_vector))
#' table(res$x_vector, res$y_vector) # Should as same as tab
#' @keywords internal
table.to.vectors <- function(x) {
  x <- as.matrix(x)
  
  # Validate input
  if (any(x < 0, na.rm = TRUE)) {
    stop("Table counts cannot be negative.")
  }
  
  # Get indices of non-zero cells
  # arr.ind = TRUE returns a matrix with columns: row, col
  indices <- which(x > 0, arr.ind = TRUE)
  
  # Get the counts (frequencies) for these cells
  counts <- x[x > 0]
  
  # Expand the indices based on the counts
  x_recovered <- rep(indices[, 1], times = counts)
  y_recovered <- rep(indices[, 2], times = counts)
  
  return(list(x_vector = x_recovered, y_vector = y_recovered))
}

Try the Upsilon package in your browser

Any scripts or data that you put into this service are public.

Upsilon documentation built on March 7, 2026, 5:07 p.m.