R/table2.R

Defines functions table2

Documented in table2

#' @title A faster version of function 'table'
#' @descriptionuse A faster version of function 'table'
#' @param x a vector to input
#' @param y another vector to input
#' @return an array
#' @examples
#' a <- c(1, 4, 2, 2, 1, 4)
#' b <- c(2, 3, 4, 2, 3, 4)
#' table2(a,b)
#' @export
table2 <- function(x, y) {
  x_val <- unique(x)
  y_val <- unique(y)
  mat <- matrix(0L, length(x_val), length(y_val))
  for (i in seq_along(x)) {
    mat[which(x_val == x[[i]]), which(y_val == y[[i]])] <-
      mat[which(x_val == x[[i]]),  which(y_val == y[[i]])] + 1L
  }
  dimnames <- list(x_val, y_val)
  names(dimnames) <- as.character(as.list(match.call())[-1])
  tab <- array(mat, dim = dim(mat), dimnames = dimnames)
  class(tab) <- "table"
  tab
}
pikachuuu108/StatComp18018 documentation built on May 19, 2019, 9:38 p.m.