mat_to_rowcolval: Convert a matrix to a data frame with rows, columns, and...

View source: R/utilities.R

mat_to_rowcolvalR Documentation

Convert a matrix to a data frame with rows, columns, and values.

Description

This function "expands" a matrix into a tidy data frame with a values column and factors for row names, column names, row types, and column types. Optionally, values can be dropped.

Usage

mat_to_rowcolval(
  .matrix,
  matvals = "matvals",
  rownames = "rownames",
  colnames = "colnames",
  rowtypes = "rowtypes",
  coltypes = "coltypes",
  drop = NA
)

Arguments

.matrix

The IO-style matrix to be converted to a data frame with rows, columns, and values.

matvals

A string for the name of the output column containing values. Default is "matvals".

rownames

A string for the name of the output column containing row names. Default is "rownames".

colnames

A string for the name of the output column containing column names. Default is "colnames".

rowtypes

A string for the name of the output column containing row types. Default is "rowtypes".

coltypes

A string for the name of the output column containing column types. Default is "coltypes".

drop

If specified, the value to be dropped from output. Default is NA. For example, drop = 0 will cause 0 entries in the matrices to be deleted from output. If NA, no values are dropped from output.

Value

A data frame with rows, columns, and values.

Examples

library(matsbyname)
data <- data.frame(Country  = c("GH", "GH", "GH"),
                   rows = c( "c1",  "c1", "c2"),
                   cols = c( "i1",  "i2", "i2"),
                   rt = c("Commodities", "Commodities", "Commodities"),
                   ct = c("Industries", "Industries", "Industries"),
                   vals = c(  11  ,  12,   22 ))
data
A <- data %>%
  rowcolval_to_mat(rownames = "rows", colnames = "cols",
                   rowtypes = "rt",   coltypes = "ct", matvals = "vals")
A
mat_to_rowcolval(A, rownames = "rows", colnames = "cols",
                 rowtypes = "rt", coltypes = "ct", matvals = "vals")
mat_to_rowcolval(A, rownames = "rows", colnames = "cols",
                 rowtypes = "rt", coltypes = "ct", matvals = "vals", drop = 0)
# This also works for single values
mat_to_rowcolval(2, matvals = "vals",
                 rownames = "rows", colnames = "cols",
                 rowtypes = "rt", coltypes = "ct")
mat_to_rowcolval(0, matvals = "vals",
                 rownames = "rows", colnames = "cols",
                 rowtypes = "rt", coltypes = "ct", drop = 0)

matsindf documentation built on May 20, 2022, 1:06 a.m.