0

I have created a fair dice simulation however when I run it, only one element is stored out of 10. I need all 10 to have a random number between 1 and 6.

dice<-function(n){

a<-numeric(n)

for(m in 1:n){

b=sample(1:6, size = n, replace = TRUE)

}
if(1==b){
a[m]<-1
}

else if(2==b){
a[m]<-2
}
else if(3==b){
a[m]<-3
}
else if(4==b){
a[m]<-4
}
else if(5==b){
a[m]<-5
}
else if(6==b){
a[m]<-6
}
a
}


x<-dice(10)

I expect an output of: 5361324164, but the actual output is: 0000000003

JaredJoss
  • 19
  • 3
  • 2
    Why don't you clarify your previous post instead of asking a new question: https://stackoverflow.com/questions/55806482/i-need-to-run-a-fair-dice-simulation-multiple-times? – markus Apr 23 '19 at 09:59
  • 1
    `sample(1:6, size = n, replace = TRUE)` is all you need to simulate n trials of a fair die. I have no clue what the rest of your code is supposed to do – Rohit Apr 23 '19 at 10:07
  • There are multiple problems with this function imo. The first one that makes the unwanted output is that you assign the values outside the for loop, so it counts from 1 to n, making random numbers in each iteration. After the last iteration, it checks the condition and assign the value to the last element. You don't have to do the whole if-else conditions afterward, you could've set the values as: a<-sample(1:6,size = n,replace = T), instead of set to variable b. You compared the numeric values to single values (6==b) which generates warning messages. – Newl Apr 23 '19 at 10:11

1 Answers1

1

I do not get why you are writing so much extra code, when this is sufficient:

# Throwing dice 10 times.
sample(c(1:6),10,replace = TRUE)
[1] 4 5 2 5 5 2 2 4 6 3

Here as a function:

dice <- function(n) {
  sample(c(1:6),n,replace = TRUE)
}

If you want to count occurences just use table:

table(dice(100))
 1  2  3  4  5  6 
11 19 15 12 20 23 
Esben Eickhardt
  • 3,183
  • 2
  • 35
  • 56
  • Why would you use replicate, when you have **size** attribute in the **sample** function? – Newl Apr 23 '19 at 10:18
  • Good point, I have having my brain in another puzzle, I helped a friend out with a week ago, where we used replicate - I will just fix it. – Esben Eickhardt Apr 23 '19 at 10:39
  • Would you know how to: Do an experiment where you throw a fair dice 100 times and count the number of ones. Also, must repeat the experiment 10^5 times and store the outcomes. This is what I have so far: x<-numeric(10^5) for(n in 1:10^5){ x[n]<-sum(dice(100)) } hist(x, main="100 Fair Rolls", xlab="Rolls", ylab="Probability", xlim=c(0,100), breaks=-1:1000+1, prob=TRUE) – JaredJoss Apr 23 '19 at 14:50