File: asMatrix.R

package info (click to toggle)
r-cran-bbmisc 1.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,256 kB
  • sloc: ansic: 176; sh: 9; makefile: 5
file content (46 lines) | stat: -rw-r--r-- 1,277 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
38
39
40
41
42
43
44
45
46
#' @title Extracts a named element from a list of lists
#'
#' @description
#' Converts a list of vectors into a matrix with vectors as columns or rows.
#'
#' @param xs [\code{list}]\cr
#'   A list of vectors of the same length.
#' @param row.names [\code{character} | \code{integer} | \code{NULL}]\cr
#'   Row names of result.
#'   Default is to take the names of the elements of \code{xs}.
#' @param col.names [\code{character} | \code{integer} | \code{NULL}]\cr
#'   Column names of result.
#'   Default is to take the names of the elements of \code{xs}.
#' @return [\code{matrix}].
#' @export
asMatrixCols = function(xs, row.names, col.names) {
  assertList(xs)
  n = length(xs)
  if (n == 0L)
    return(matrix(0, nrow = 0L, ncol = 0L))
  assertList(xs, types = "vector")

  m = unique(viapply(xs, length))
  if (length(m) != 1L)
    stopf("Vectors must all be of the same length!")

  if (missing(row.names)) {
    row.names = names(xs[[1L]])
  }

  if (missing(col.names)) {
    col.names = names(xs)
  }

  xs = unlist(xs)
  dim(xs) = c(m, n)
  rownames(xs) = row.names
  colnames(xs) = col.names
  return(xs)
}

#' @rdname asMatrixCols
#' @export
asMatrixRows = function(xs, row.names, col.names) {
  t(asMatrixCols(xs, row.names = col.names, col.names = row.names))
}