v2m: (Atomic) Vector to Matrix

View source: R/str2str_functions.R

v2mR Documentation

(Atomic) Vector to Matrix

Description

v2m converts an (atomic) vector to a single row or single column matrix. The matrix will be the same typeof as the atomic vector. The benefit of v2m over as.matrix.default is that the dimension along which the vector is binded can be either rows or columns, whereas in as.matrix.default it can only be binded along a column.

Usage

v2m(v, along = 2, rtn.dim.nm = NULL, check = TRUE)

Arguments

v

(atomic) vector.

along

numeric vector of length 1 that is equal to either 1 or 2 specifying which dimension to bind v along. 1 means that v is binded along rows (i.e., dimension 1) into a one row matrix. 2 means that v is binded along columns (i.e., dimension 2) into a one column matrix.

rtn.dim.nm

character vector of length 1 specifying what dimname to use for the dimension of length 1 in the returned matrix. If along = 1, then rtn.dim.nm will be the single rowname. If along = 2, then rtn.dim.nm will be the single colname. If NULL, then the dimension of length 1 has no dimname.

check

logical vector of length 1 specifying whether to check the structure of the input arguments. For example, check whether v is an atomic vector. This argument is available to allow flexibility in whether the user values informative error messages (TRUE) vs. computational efficiency (FALSE).

Value

matrix with typeof = typeof(v). If along = 1, then the dimensions = c(1L, length(v)) and dimnames = list(rtn.dim.nm, names(v)). If along = 2, then the dimensions = c(length(v), 1L) and dimnames = list(names(v), rtn.dim.nm).

Examples

mtcars2 <- as.matrix(mtcars, rownames.force = TRUE) # to make sure dimnames stay in the example
v2m(mtcars2[, "mpg"])
identical(x = v2m(mtcars2[, "mpg"]),
   y = as.matrix(mtcars2[, "mpg"])) # default = as.matrix.default()
v2m(mtcars2[, "mpg"], along = 1)
identical(x = v2m(mtcars2[, "mpg"], along = 1),
   y = t(as.matrix(mtcars2[, "mpg"]))) # = t(as.matrix.default())
v2m(v = mtcars2[, "mpg"], rtn.dim.nm = "mpg")

str2str documentation built on Nov. 21, 2023, 1:08 a.m.