Skip to contents

Coerces an object to a CompositionMatrix object.


as_composition(from, ...)

# S4 method for matrix

# S4 method for data.frame
as_composition(from, samples = NULL, groups = NULL)



A matrix or data.frame to be coerced.


Currently not used.


An integer giving the index of the column to be used for sample identification: allows to identify replicated measurements. If NULL (the default), row names will be used as sample IDs.


An integer giving the index of the column to be used to group the samples. If NULL (the default), no grouping is stored.


A CompositionMatrix object.


The CompositionMatrix class has special slots (see vignette("manual")):

  • samples for repeated measurements/observation,

  • groups to group data by site/area.

When coercing a data.frame to a CompositionMatrix object, an attempt is made to automatically assign values to these slots by mapping column names (case insensitive, plural insensitive). This behavior can be disabled by setting options(nexus.autodetect = FALSE) or overridden by explicitly specifying the columns to be used.


All non-numeric variable will be removed.

See also

Other compositional data tools: as_amounts(), closure()


N. Frerebeau


## Create a count matrix
A1 <- matrix(data = as.numeric(sample(1:100, 100, TRUE)), nrow = 20)

## Coerce to compositions
B <- as_composition(A1)

## Row sums are internally stored before coercing to relative frequencies
## (use get_totals() to retrieve these values)
## This allows to restore the source data
A2 <- as_amounts(B)

## Coerce to an S3 data.frame
X <- data.frame(B)
#>            col1      col2      col3       col4       col5 samples
#> row1 0.06250000 0.2416667 0.3000000 0.33750000 0.05833333    row1
#> row2 0.19217082 0.1530249 0.2526690 0.12811388 0.27402135    row2
#> row3 0.28630705 0.1203320 0.3734440 0.02489627 0.19502075    row3
#> row4 0.25885559 0.1771117 0.1035422 0.19618529 0.26430518    row4
#> row5 0.05666667 0.2033333 0.2400000 0.16666667 0.33333333    row5
#> row6 0.27483444 0.1788079 0.2880795 0.22847682 0.02980132    row6