File: vec2tab.R

package info (click to toggle)
r-cran-latte 0.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 564 kB
  • sloc: makefile: 2
file content (37 lines) | stat: -rw-r--r-- 1,001 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#' Vector to array conversion
#'
#' Convert a vector into an array given a set of dimensions; it therefore simply
#' wraps [base::aperm()] and [base::array()].
#'
#' This function converts an array (or a multi-way contingency table) into a
#' vector, using a consistent ordering of the cells. The ordering of the cells
#' is lexicographic and cannot be specified by the user.
#'
#' @param vec A vector
#' @param dim The desired array dimensions, oftentimes a vector of the number of
#'   levels of each variable in order
#' @return An array
#' @export
#' @seealso [tab2vec()], [base::aperm()], [base::array()]
#' @examples
#'
#' data(Titanic)
#' str( Titanic )
#' str( tab2vec(Titanic) )
#' 
#' # convert it back into a table (names are removed)
#' vec2tab(
#'   tab2vec(Titanic), 
#'   dim(Titanic)
#' )
#' 
#' # check that they are the same
#' all( vec2tab(tab2vec(Titanic), dim(Titanic)) == Titanic )
#'
#' 
vec2tab <- function(vec, dim){
  aperm(
    array(vec, rev(dim)),
    length(dim):1
  )
}