Natalie
Natalie

Reputation: 43

HW assignment for learning R from scratch

So I am taking a course that requires learning R and I am struggling with one of the questions:

In this question, you will practice calling one function from within another function. We will estimate the probability of rolling two sixes by simulating dice throws. (The correct probability to four decimal places is 0.0278, or 1 in 36).

I am fine with part one, or at least I think so, so this is what I have

roll.dice<-function(ndice)  
{
  roll<-sample(1:6,ndice,TRUE)
  return(roll)
}
roll.dice(ndice=2)

but I am struggling with part two. This is what I have so far:

prob.sixes<-function(nsamples)  {
  j<-vector
  j<-0
  roll.dice(nsamples)
  if (roll.dice==6) {
    j<-j+1
    return(j)
  }
}
prob.sixes(nsamples=3)

Sorry for all the text, but can anybody help me?

Upvotes: 0

Views: 109

Answers (1)

andrechalom
andrechalom

Reputation: 737

Your code has a couple of problems that I can see. The first one is the interpretation of the question. The question says:

Now create a function prob.sixes() with parameter nsamples, that first sets j equal to 0, and then calls roll.dice() multiple times (nsample number of times).

Check on your code, are you doing this? Or are you calling roll.dice() a single time? Look for ways to do the same thing (in your case, roll.dice) several times; you may consider the function for. Also, here, you need to store the result of this function on a variable, something like

rolled = roll.dice(2)

Second problem:

Every time that roll.dice() returns two sixes, add one to j.

You are checking if roll.dice==6. But this has two problems. First, roll.dice is a function, not a variable. So it will never be equal to 6. Also, you don't want to check if this variable is equal to six. You should ask whether this variable is equal to a pair of sixes. How can you write "a pair of sixes"?

Upvotes: 2

Related Questions