#Births,PREV_BIRTH,PREV_TWO_BIRTH,Min_Birth_Group,Year,County #Uncomment to test the function step by step #REG_MODEL <- BIRTH_MOD;REG_DATA <- BIRTH_DATA;NUM_SIMS=1 BIRTH_SIM <- function(REG_MODEL,REG_DATA,NUM_SIMS=1){ 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(MALE,BIRTHS-MALE) rownames(RES) <- "0" colnames(RES) <- c("Num_Male","Num_Female") #%>% as_tibble #colnames(RES) <- c("Num_Male","Num_Female") #"0" return(RES) }