R/community_generate.R

Defines functions community_generate

Documented in community_generate

#' Generate a community sampled from regional pool
#' @description The community is sampled from regional species pool. The output is
#' modified so it fits the argument format for CR_model().
#' @name commnity_generate
#' @param I inocula drop size
#' @param threshold minimal detectable size or extinction threshold of microbes
#' @param seed seed for sampling
#' @return a named vector
#' @seealso \url{https://github.com/Chang-Yu-Chang/micro.crm} for package page, \code{\link{community_coalesce}}
#' @examples
#' # Load packages and example parameters
#' library(tidyverse)
#' data(example_parameter)
#'
#' # Build regional species pool
#' pool_build(save_data = FALSE)
#'
#' # Generate a community sample from pool
#' community_generate(pool = regional_pool, I = 1e-2, threshold = 1e-4)
#' 
#' \dontrun{
#' community_generate("bad")
#' }

community_generate <- function(
                               pool = regional_pool, # Pool is a named vector with the probability of sampling one species
                               I = .01, # Inocula drop size
                               threshold = 1e-5,
                               seed = 1) {
  #
  stopifnot(is.vector(pool))

  # Set seed
  set.seed(seed)

  # Sample a vector
  x <- sample(sub("\\w", "", names(pool)) %>% as.numeric(),
    I / threshold,
    replace = T, prob = pool
  ) %>%
    table() %>%
    as.list() %>%
    unlist()

  # Named vector with consumer intiatives and multiply by name
<<<<<<< HEAD
  x <- setNames(
    x * threshold,
    paste0("X", sprintf("%05d", as.numeric(names(x))))
  )

=======
  x <- setNames(x * threshold, paste0("X", sprintf("%05d", as.numeric(names(x)))))
  
>>>>>>> 381875eedd7472bfbaf2cfd62d780ca03ff9b601
  # Return species name and size
  return(x)
}
Chang-Yu-Chang/MigrationCommunity documentation built on Aug. 13, 2019, 9:41 p.m.