R/abund.R

# From an output object of 'forward()' or 'coalesc()', computes vector of
# abundances per species
abund <- function(x) {
  if (!is.list(x)) {
    stop("The input argument must be a list of communities")
  }
  
    rel_abund_list <-  lapply(x, function(y) {
      
      if (is.list(y) & !is.data.frame(y) & !is.matrix(y)) {
        rel_abund <- lapply(y, .get_rel_abund)
      } else {
        rel_abund <- .get_rel_abund(y)
      } 
      
      return(rel_abund)
    })
    
    if (sum(is.na(rel_abund_list)) + sum(is.null(rel_abund_list)) != 0) {
      warning("Some communities were undefined; returning NA abundances")
    }
    
    return(rel_abund_list)
}

# Internal function to compute relative abundances from a community data.frame
.get_rel_abund <- function(comdf) {
  
  if (is.data.frame(comdf) | is.matrix(comdf)) {
    rel_abund <- as.data.frame(table(comdf[, "sp"]), stringsAsFactors = FALSE)
    colnames(rel_abund) <- c("sp", "ab")
    rel_abund$relab <- rel_abund$ab / nrow(comdf)
  } else {
    rel_abund <- NA
  }
  
  return(rel_abund)
}

Try the ecolottery package in your browser

Any scripts or data that you put into this service are public.

ecolottery documentation built on May 2, 2019, 9:34 a.m.