#Births,PREV_BIRTH,PREV_TWO_BIRTH,Min_Birth_Group,Year,County #Uncomment to test the function step by step #REG_MODEL <- MOD_BIRTHS;REG_DATA <- FIRST_PREDICT_YEAR_POPULATION_DATA;NUM_SIMS=1 BIRTH_SIM <- function(REG_MODEL,REG_DATA,NUM_SIMS=1){ predict(REG_MODEL,newdata=REG_DATA) C_PREDICT <- predict(REG_MODEL,REG_DATA,interval = "prediction",level=0.95) PRED_MEAN <- C_PREDICT$fit SE_PRED <- (C_PREDICT$ci_high-C_PREDICT$ci_low)/3.92 YEAR <- REG_DATA %>% pull(Year) %>% unique BIRTHS <- round(exp(rnorm(NUM_SIMS,mean=PRED_MEAN,sd=SE_PRED))) MALE <- sapply(1:NUM_SIMS,function(x){ rbinom(1,BIRTHS[x],prob=0.5)}) RES <- cbind(rep(YEAR,NUM_SIMS),rep(0,NUM_SIMS),MALE,BIRTHS-MALE) %>% as_tibble colnames(RES) <- c("Year","Age","Num_Male","Num_Female") return(RES) }