Loops for Beginner

#Write a function that simulates the outcome of one play at the slot machine,
#i.e. either returns 0 or 2 with probability p and 1-p respectively.

I wrote the following code:

Slot <- function(nflips,p)
x <- runif(nflips)

Now, if I start with $10, and decide to play until you either win $20, or lose all money. Write a while loop to simulate this process. In the end you will have either $20 or $0. How many times did you play? Assuming p=0.05

I looked at different sources on the web and came up with:
while (i<=10)
{x <- runif(begin)

Since I have no coding experience, would appreciate some tips on how to use 'while' statement; especially here when we have 2 conditions i.e. either I lose $10 or win $20.

Thank you.


Welcome to the RStudio community!

It's nice of you to be honest and label this question as homework! Do know however we have policies around helping out in such cases:

So I can give you some tips, but no solutions :slight_smile:

  • The sample function is a great way to have a random pick out of a 'bag' of options, you can even set the probability of each outcome.
  • A while loop keeps on running until its condition to continue is no longer met. If you like to consider multiple conditions, you can chain them together with logical operators AND, OR, who are in R functions represented as &, | respectively. E.g. x == 0 & y < 5
  • If you're not sure what is happening in a while loop, either run the code inside manually or add a print statement to see the intermediate values appear of any variables of interest. E.g. print(x)

Let's see if this already helps :slight_smile:
Good luck!

1 Like

Thanks a lot for clarifying the policies for posting on this forum. I will abide by them... Yes, assignments are a part of the course I am taking, but learning the basics is the aim. The course is titled - 'Using R for Biostatistics I'.
I appreciate your tips and yes I agree 'No solutions!'

1 Like

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