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)
<<<<<<< HEAD
#'
#' #
community_coalesce <- function(
                               ...) {
  coms <- list(...)

=======
#' @export


#
community_coalesce <- function(
  ...
){
>>>>>>> 381875eedd7472bfbaf2cfd62d780ca03ff9b601
  # Check that the input number of community must be larger than 2
  coms <- list(...)
  stopifnot(length(coms) >= 2)
<<<<<<< HEAD
=======
  
  # Sort the vectors by names. R first and then X
  coms <- lapply(coms, function(x) x[order(factor(names(x), levels = c(paste0("R", sprintf("%03d", 1:P)), paste0("X", sprintf("%05d", 1:S_pool)))))])
>>>>>>> 381875eedd7472bfbaf2cfd62d780ca03ff9b601

  # 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 species 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 Aug. 13, 2019, 9:41 p.m.