matrix_: Fast in-place transformation to a matrix (without copy)

Description Usage Arguments Value Note See Also Examples

View source: R/array_transform.R

Description

matrix_ transforms its data argument to a matrix by reference. If the length of data remains the same, no copy is made at all, and it invisibly returns the matrix. This is mostly useful for manipulating interim objects in functions, and should not be used for interactive analyses.

Usage

1
2
3
4
5
6
7
8
9
matrix_(
  x,
  nrow,
  ncol,
  byrow = FALSE,
  dimnames = NULL,
  force_length = TRUE,
  arg_check = TRUE
)

Arguments

x

a data vector, matrix or array

nrow

the desired number of rows

ncol

the desired number of columns

byrow

logical. If FALSE (the default), the matrix is filled by columns, otherwise the matrix is filled by rows. If TRUE, it results in an error!

dimnames

A dimnames attribute for the matrix: NULL or a list of length 2 giving the row and column names respectively. The list can be named, and the list names will be used as names for the dimensions. An empty list is treated as NULL, and a list of length one as row names.

force_length

logical. If TRUE (the default), matrix_ checks if length(x)==nrow*ncol. If not, x is recycled or subsetted to the desired length.

arg_check

logical indicating if argument checks should be performed (TRUE, the default). Do not set to FALSE unless you really know what you are doing!

Value

matrix_ invisibly returns a matrix without duplicating the input values.

Note

Use matrix_ with extra care because it modifies in place all objects which x refers to. If you want to avoid this, call x <- copy(x) before calling matrix_ or use the standard way as described in the Note section of matrix. However, for input objects created on-the-fly (e.g. a temporary vector), matrix_ is safe and more compact than the latter solution, and can be many times faster than matrix.

See Also

array_ for in-place transformation of x to an array (without copy) and matrix for creating a new matrix without modifying the original input

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# create two vectors
x <- y <- 1:10

# suppose 'x' should be a 2x5 matrix
matrix_(x, 2, 5)
str(x)

# however, since 'x' was referenced to 'y', 'y' has been changed, too
str(y)

# compare the timing for matrix creation
if (require(microbenchmark)) {
    microbenchmark(
        matrix = matrix(0L, 1e3, 1e3),
        matrix_ = matrix_(0L, 1e3, 1e3),
        times = 100L
    )
}

tdeenes/eegR documentation built on April 19, 2021, 4:17 p.m.