R/community_generate.R

Defines functions community_generate

Documented in community_generate

#' Generate a community sampled from regional pool
#' @description The commnity 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
#' @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)
#' @export

# 
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
  x <- setNames(x * threshold,
                paste0("X", sprintf("%05d", as.numeric(names(x)))))
  
  # Return species name and size
  return(x)
}
Chang-Yu-Chang/MigrationCommunity documentation built on April 22, 2019, 7:36 p.m.