# Grab values from a given cumulative probabilites (Sampling)

Hi guys,

I have a question and hope somebody can help me out please!
I have a data frame like this:

``````test <- data.frame(Names = 1:5,
weight = c(0.1, 0.05, 0.2, 0.3, 0.3),
prob = c(0.105263158, 0.052631579, 0.210526316, 0.315789474, 0.315789474),
cum_prob = c(0.105263158, 0.157894737, 0.368421053, 0.684210526, 1))
``````

What I want is to randomly get the values "Names" corresponding only from the data\$cum_prob by runif(1) and store it via loop. E.g. if the value comes up 0.7xx it should store the value 4, if it comes value 0.15 then value 2 should be stored. This is what I've coded so far.

``````    for (a in 1:nsim){

for (b in 1:qpois(runif(1), lambda)){

iteration[b,] <- ?????????????

}

table1[a,] <- sum(iteration, na.rm = T)
iteration[,1] <- NA

}
``````

But I really dont know how to do it : / I've checked on some sites with the sample-function but it doesnt help me so far.

I hope somebody can give me a hint please. I would be grateful for any help for this code.

Kind regards
sam1

I think I solved it!

for (a in 1:nsim){

``````    for (b in 1:qpois(runif(1), lambda)){

iteration[b,] <- test[match.closest(runif(1),test\$cum, prob),1]

}

table1[a,] <- sum(iteration, na.rm = T)
iteration[,1] <- NA

}
``````

but this code takes reaaaaally long. I even loop this loop another 10 times to estimate the mean of the values. Is there a way to make it faster?

With kind regards,
sam1

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.