Assume I have the following data structure:
sl_sev_disbn <- data.frame("lower_band" = c(0,10e6,20e6,30e6,0,0,0),
"upper_band" = c(10e6,20e6,30e6,40e6,0,0,0),
"prob" = c(0.56521739,0.34782609,0.08212560,0.00483092,0,0,0),
"band" = c(1,2,3,4,5,6,7))
I want to randomly sample a "band" from this dataframe using the given probabilities as weights. From this band, I want to sample a randomly number uniformally from the lower and upper bands given and store every sample and return it into a vector. I have the following code:
rsuper_lrg_disbn <- function(n = 1,df){
band_sample <- sample(x = df$band, size = n, prob = df$prob,replace=TRUE)
vals <- c()
for (band in band_sample){
filt_df <- df[df$band == band,] #filter to randomly selected band
loss <- runif(1,min=filt_df$lower_band,max=filt_df$upper_band)
vals <- c(vals,loss)
}
return(vals)
}
Then using it would be like: rsuper_lrg_disbn(n=2,sl_sev_disbn)
However, this code slows down massively if I use n very large such as n = 1e6.
Does anyone know how I can speed this up?