gather_matrix: Transform a matrix into a long ("tidy") data frame

gather_matrixR Documentation

Transform a matrix into a long ("tidy") data frame

Description

Converts a matrix into a data frame with one row for each matrix entry and three columns. This is the same idea as the gather function from the tidyr package, but for the matrix special case. The result is in row-major order by default. An ordinary matrix m is unrolled into triplets i, j, m_{ij}. If row or column names are present they are swapped in for the numeric indices, or you can supply these directly.

Usage

gather_matrix(
  m,
  row_values = rownames(m),
  col_values = colnames(m),
  col_names = c("row_key", "col_key", "value"),
  row_major = TRUE
)

Arguments

m

matrix (or Matrix: but sparse matrices will be filled in)

row_values

values corresponding to row indices. By default the row names of m are used, or, if these are missing, the row indices themselves.

col_values

similarly, for columns.

col_names

names for the columns of the resulting data frame

row_major

unroll m row by row or column by column? By row is the default, though by column may be faster.

Value

a data frame with three columns and one row for every entry of m.

Examples

m <- matrix(1:4, ncol=2, byrow=TRUE)
gather_matrix(m)


agoldst/dfrtopics documentation built on July 15, 2022, 4:13 p.m.