Skip to contents

Shrink a numeric matrix across groups of rows, by applying a summary function.

Usage

shrink_matrix(
  x,
  groupBy,
  shrink_func = function(x) {
     mean(x, na.rm = TRUE)
 },
  return_class = c("data.frame", "matrix"),
  verbose = FALSE,
  ...
)

Arguments

x

numeric matrix

groupBy

character or factor vector of group labels, whose length equals nrow(x). These values will become rownames in the output data.

shrink_func

function that takes vector input and returns single value output. The vector class can be checked, in order to call a function on numeric or character data separately, as needed.

return_class

character string indicating the return data type.

  • "data.frame" returns a data.frame whose first column contains entries from groups.

  • "matrix" returns a numeric matrix whose rownames are entries from groups.

verbose

logical indicating whether to print verbose output.

...

additional arguments are ignored.

Value

data.frame or matrix based upon argument return_class.

Details

This function is mainly a wrapper to use the amazingly fast data.table package, with the ability to provide a custom function to shrink row values.

The default function uses mean(x, na.rm=TRUE) so that NA values are ignored where possible.

This function applies the same shrink_func to all columns, and it optimal for numeric values. For more control over which function to apply to specific columns, see shrinkDataFrame().

Trivia: This function is identical to splicejam::shrinkDataFrame() except that the default shrink_func includes na.rm=TRUE and no longer calls an internal function, since that is not permitted by CRAN package guidelines.