I need help speeding up a simple function that uses which() and rbinom() to calculate how long a nest survives for, based on a daily survival probability and nesting period. I use this in a data.table simulation in a shiny app, and this line really, really slows things down.
The offending function is below - it calculates how long a nest will survive given a daily survival probability and an incubation period. The function generates 1s and 0s for each day, with a 1 being continued survival and 0 being failure. If the nest doesn't fail, the function returns the full incubation period, but if it does fail, it returns the day that the nest fails, by telling me the position of the first 0.
# specify parameters for function
period<-28
prob.surv<-0.98
# survival function that returns how long a nest survives for in days
survival<-function(period,prob.surv){
which(rbinom(period,1,prob.surv)==0)[1] %>% replace(is.na(.), period)}
I then use this in a longer function using data.table - a simplified example is here:
library(data.table)
# make a dt
dat <- data.table(nests = 1:4000)
# date incubation starts
dat[,inc.start:= round(rnorm(n=nrow(dat), 80, sd = 2))]
# date incubation ends
dat[,inc.end:= inc.start + (replicate(n=nrow(dat), survival(28, 0.98)))]
Not sure that using replicate() like that is very good, but can't work out a better solution.
Because the function is used 3/4 times in total in the simulation, it is a really big bottleneck in the code.
Any advice on either how to speed up the survival() function, or to use it more efficiently in data.table would be much appreciated!