I need to run a fair dice simulation multiple time

2019-09-19 23:47发布

问题:

I have a program that simulates a dice roll 100 times. I need to know how to run this program 10^5 times, I think it is something to do with numeric.

 set.seed(123)

 x <- sample(1:6, size=100, replace = TRUE)

 hist(x,
 main="10^6 fair rolls",
 xlab = "Dice Result",
 ylab = "Probability",
 xlim=c(0.5,6.5),
 breaks=-1:100+.5,
 prob=TRUE )

回答1:

As suggested by @markus, you can use replicate:

set.seed(123)

nTime <- 10^5

x <- replicate(nTime, sample(1:6, size=100, replace = TRUE))

hist(x,
     main="10^6 fair rolls",
     xlab = "Dice Result",
     ylab = "Probability",
     xlim=c(0.5,6.5),
     breaks=-1:100+.5,
     prob=TRUE )