Population_Study/Scripts/Load_Custom_Functions/Birth_Simulation_Functions.r
2025-12-03 17:27:42 -07:00

19 lines
744 B
R

#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)
}