Skip to contents

Calculates an element-wise median over a list of matrices or CompadreMat objects of constant dimension.

Usage

mat_median(x, na.rm = FALSE)

mpm_median(x, na.rm = FALSE)

Arguments

x

A list of matrices or, for mpm_sd a list of `CompadreMat` objects, all of the same dimension

na.rm

Logical indicating whether missing values should be excluded (see Details). Defaults to FALSE.

Value

A matrix containing the median of each element across all matrices in the list

Details

The difference between function mat_median) and (mpm_median is that mat_median takes input as a list of matrices (e.g., a list of **A** matrices) while mat_median takes input as a list of `CompadreMat` objects and thus calculates the mean matrices for both the **A** matrix and its submatrices (**U**, **F**, **C**).

If na.rm == TRUE, missing values are ignored in the calculation of the mean matrix. If na.rm == TRUE and a given element is NA in every matrix within x, the value returned for that element will be 0.

Author

Darren Norris

Owen R. Jones <jones@biology.sdu.dk>

Examples

# set seed for repeatability
set.seed(42)

# create a function that generates a matrix with random values
create_matrix <- function() {
  matrix(runif(9, 0, 1), nrow = 3)
}

# use replicate() to call the create_matrix() function 20 times
mat_list <- replicate(20, create_matrix(), simplify = FALSE)

# get the median matrix
mat_median(mat_list)
#>           [,1]      [,2]      [,3]
#> [1,] 0.5731547 0.7219267 0.5627341
#> [2,] 0.5862329 0.5077667 0.5146376
#> [3,] 0.5720870 0.4575122 0.6933612

# If the matrices are in an RCompadre object, extract them using `matA` before
# passing to `mat_median`
my_compadre <- cdb_build_cdb(mat_a = mat_list)
#> Warning: Metadata does not include a `SpeciesAccepted` column, so number
#>               of species not provided when viewing object.
mat_median(matA(my_compadre))
#>           [,1]      [,2]      [,3]
#> [1,] 0.5731547 0.7219267 0.5627341
#> [2,] 0.5862329 0.5077667 0.5146376
#> [3,] 0.5720870 0.4575122 0.6933612