# A 4-sample x 5-OTU matrix with samples in rows.
counts <- matrix(c(0,0,0,0,0,8,9,10,5,5,5,5,2,0,0,0,6,5,7,0), 4, 5,
dimnames = list(LETTERS[1:4], paste0('OTU', 1:5)))
counts
rowSums(counts)
# Rarefy all samples to a depth of 13.
# Note that sample 'A' has 0 counts and is dropped.
r_mtx <- rarefy(counts, depth = 13, seed = 1)
r_mtx
rowSums(r_mtx)
# Keep zero-sum rows and columns by setting `drop = FALSE`.
rarefy(counts, depth = 13, drop = FALSE, seed = 1)
# Rarefy to the depth of the 2nd most abundant sample (B, depth=22).
rarefy(counts, n_samples = 2, seed = 1)
# Perform 3 independent rarefactions.
r_list <- rarefy(counts, depth = 13, times = 3, seed = 1)
length(r_list)
r_list[[1]]
# The class of the input matrix is preserved.
if (requireNamespace('Matrix', quietly = TRUE)) {
counts_dgC <- Matrix::Matrix(counts, sparse = TRUE)
class(counts_dgC)
r_dgC <- rarefy(counts_dgC, depth = 13, seed = 1)
class(r_dgC)
}
Run the code above in your browser using DataLab