How do I create a loop based off a function?

Basically, I have a probability that a specific coloured ball is being chosen being (1/n(n+1)).

I am completely foreign to R and have no idea how to run a loop using the formula that I found to simulate the number of turns it would take to pick the specific coloured ball.

It would be great if someone could help me with writing the code or at least point me in the right direction!

What is N in the formula? And what is the formula giving the probability of? Being chosen among how many balls? How many rounds?

If you don't have a specific number of repeats or list of things to go through before you start the loop, then you probably want to use a While loop instead.

It sounds like this is part of a schoolwork assignment?

I'd recommend using a while loop. In the case described in part (b), the structure of the code looks something like this. I'm going to write the code for the standard geometric distribution case, and I think you can extend to your case.

# returns the number of turns before selecting something with probability p
simulation <- function(p) {
  number_of_turns <- 1
  # exit the loop with probability p, which means
  # stay in the loop with probability 1-p
  while (runif(1) > p) {
    # account for the turn and try again
    number_of_turns <- number_of_turns + 1
  }
  number_of_turns
}

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