Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save mrdwab/10a41d7d77a0d3b3e26d to your computer and use it in GitHub Desktop.

Select an option

Save mrdwab/10a41d7d77a0d3b3e26d to your computer and use it in GitHub Desktop.
Convert binary matrices by row to integer values (and related functions)
#' Convert a binary matrix to a vector of integers (by row)
#'
#' The \code{mat2int} function converts a binary matrix to a vector of integers.
#'
#' @param inmat The input matrix.
#' @return A vector of integers.
#' @author Ananda Mahto
#' @seealso \code{\link{strtoi}}.
#' @examples
#'
#' x1 <- expand.grid(replicate(5, c(0, 1), FALSE))
#' x2 <- expand.grid(replicate(8, c(0, 1), FALSE))
#' mat2int(x1)
#' mat2int(x2)
#'
#' @export mat2int
mat2int <- function(inmat) {
if (!is.matrix(inmat)) inmat <- as.matrix(inmat)
if (!all(as.matrix(inmat) %in% c(0, 1))) stop("invalid input matrix")
as.integer(inmat %*% 2^((ncol(inmat)-1):0))
}
NULL
#' Convert a vector of integers into a binary matrix
#'
#' The \code{int2mat} function converts a vector of integers into a binary matrix.
#'
#' @param invec The input vector.
#' @param ncol The number of columns expected in the resulting matrix.
#' @return A binary matrix.
#' @author Ananda Mahto
#' @examples
#'
#' x1 <- expand.grid(replicate(5, c(0, 1), FALSE))
#' v1 <- mat2int(x1)
#'
#' int2mat(v1, 5)
#'
#' @export int2mat
int2mat <- function(invec, ncol) {
matrix((rep(invec, each = (ncol)) %/%
(2^((ncol-1):0)) %% 2), ncol = ncol, byrow = TRUE)
}
NULL
#' Creates a key of a binary matrix with the row-wise integer representation and column names
#'
#' The \code{bin2key} function creates a lookup key containing the integer representation
#' of the rows and the column names for a binary matrix.
#'
#' @param inmat The input matrix.
#' @param sep The character to separate the relevant column names. Defaults to \code{sep = "/"}.
#' @return A two column \code{data.frame} where \code{"intval"} is the integer value
#' that represents the binary combination of the row and where \code{"key"} is the column names
#' where a value of \code{1} is found.
#' @note This returns a "key" of just the unique rows of the matrix that can later be merged
#' with the original dataset if required.
#' @author Ananda Mahto
#' @examples
#'
#' ## row 5 is duplicated
#' withDupes <- data.frame(v1 = c(1, 1, 1, 1, 1),
#' v2 = c(1, 0, 1, 0, 1),
#' v3 = c(1, 0, 0, 1, 1))
#' withDupes
#' bin2key(withDupes, "+")
#'
#' @export bin2key
bin2key <- function(inmat, sep = "/") {
x <- unique(inmat)
data.frame(intval = mat2int(x),
key = apply(x, 1, function(y) {
paste(names(x)[as.logical(y)], collapse = sep)
}))
}
NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment