R/community_coalesce.R

Defines functions community_coalesce

Documented in community_coalesce

#' Coalesce the communities
#' @description This function coalesce the communities that are put together 
#' for the consumer-resource dynamics
#' @name community_coalesce
#' @param ... input must be named vectors. Each named vector has value indicate the
#'  biomass, whereas names are resource or consumer.
#' consumer or resource
#' @return a united named vector or all input communities
#' @examples
#' com1 <- community_generate(I = .01, threshold = 1e-3)
#' com2 <- community_generate(I = .01, threshold = 1e-3, r = 2)
#' com3 <- community_generate(I = .01, threshold = 1e-3, r = 3)
#' community_coalesce(com1, com2, com3)


# Load packages
library(tidyverse)
library(deSolve)
library(data.table)

#
community_coalesce <- function(
  ...
){
  coms <- list(...)
  
  # Check that the input number of community must be larger than 2
  stopifnot(length(coms) >= 2)
  
  # Create the first united community by community 1 and 2
  com_union <- union(names(coms[[1]]), names(coms[[2]])) %>% sort()
  com_union <- setNames(rep(0, length(com_union)), com_union)
  
  for (i in 1:length(coms)) {
    # New species of a community
    com_setdiff <- setdiff(names(coms[[i]]), names(com_union))
    # Concatenate the community
    com_union <- c(com_union, setNames(rep(0, length(com_setdiff)), com_setdiff))
    # Sort by speceis name
    com_union <- com_union[order(names(com_union))]
    # Add value
    com_union[names(com_union) %in% names(coms[[i]])] <-
      com_union[names(com_union) %in% names(coms[[i]])] + coms[[i]]
  }
  return(com_union)
}
Chang-Yu-Chang/MigrationCommunity documentation built on Sept. 8, 2018, 8:30 p.m.