Apologies if this is a little convoluted. I'm running an agent based simulation and would like to 'promote' n individuals at each timestep. I have a logistic model which, for each individual, gives me a predicted probability of their being promoted. I want to randomly select n individuals, weighted by their promotion probabilities, for promotion.
At present, I run this code:
test_frame <- data.frame(
id = seq(1,10),
promote_prob = sample(c(0.0000001, 0.5), 10, TRUE)
)
id_list <- data.frame(n = sample(test_frame$id,
nrow(test_frame),
prob = test_frame$promote_prob),
rank = seq(1, nrow(test_frame)))
test_frame %>%
left_join(id_list, by = c("id" = "n")) %>%
mutate(promote_flag = ifelse(rank < 3, 1, 0))
ID_list produces a random, weighted ranking of all rows in the table, based on their promotion probability. But the join operation makes this process very slow - it's the slowest step in the simulation by far. Is there a way to vectorise this series of steps? My experiments with this have not come to much - e.g.:
test_frame %>%
mutate(n = sample(seq(1:nrow(test_frame)), nrow(test_frame), FALSE, promote_prob)) %>%
mutate(promote = ifelse(n < 3, 1, 0))