m2d: Matrix to Data-Frame

View source: R/str2str_functions.R

m2dR Documentation

Matrix to Data-Frame

Description

m2d converts a matrix to a data.frame. The benefit of m2d over as.data.frame.matrix is that it provides the col argument, which allows the columns of the data.frame to be the columns of the matrix (i.e., col = 2), the rows of the matrix (i.e., col = 1), or the expanded matrix (i.e., col = 0).

Usage

m2d(m, col = 2, stringsAsFactors = FALSE, check = TRUE)

Arguments

m

matrix

col

numeric vector of length 1 that is equal to either 0, 1, or 2. col specifies what dimension from m should be the columns of the returned data.frame. If col = 2, then the columns of m (i.e., dimension 2) are the columns of the returned data.frame. If col = 1, then the rows of m (i.e., dimension 1) are the columns of the returned data.frame. If col = 0, neither of the m dimensions are the columns and instead the matrix is expanded by reshape::melt.array such that in the returned data.frame the first column is rownames(m), the second column is colnames(m, and the third column is the elements of m. If any dimnames(m) are NULL, then they are replaced with the positions of the dimensions.

stringsAsFactors

logical vector of length 1 specifying whether any resulting character columns in the return object should be factors. If m is a character matrix and stringsAsFactors = TRUE, then all columns in the returned data.frame will be factors. If col = 0 and stringsAsFactors = TRUE, then the first two columns in the returned data.frame specifying dimnames(m) will be factors.

check

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

Value

data.frame with rownames and colnames specified by dimnames(m) and col. If col = 0, then the rownames are default (i.e., "1","2","3", etc.) and the colnames are the following: the first two columns are names(dimnames(m)) (if NULL they are "rownames" and "colnames", respectively) and the third is "element".

Examples

mtcars2 <- as.matrix(mtcars, rownames.force = TRUE) # to make sure dimnames stay in the example
m2d(mtcars2) # default
m2d(m = mtcars2, col = 1) # data.frame columns are matrix rownames
m2d(m = mtcars2, col = 0) # data.frame columns are the entire matrix
mat <- cbind(lower = letters, upper = LETTERS)
m2d(mat)
m2d(mat, stringsAsFactors = TRUE)
m2d(mat, col = 0)
m2d(mat, col = 0, stringsAsFactors = TRUE)

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