showkey
showkey

Reputation: 328

How to get the right simulation in R

Question:
Suppose the numbers in the following random number table correspond to people arriving for work at a large factory. Let 0,1,and 2 be smokers and 3-9 be nonsmokers. After many arrivals, calculate the total relative frequency of smokers .

here is my R code to simulate the total relative frequency of smokers.

simulation<-function(k){
    x<-round(runif(k)*10)
    return  (length(x[x<3])/k)}

> simulation(100)
[1] 0.27
> simulation(1000)
[1] 0.244
> simulation(10000)
[1] 0.2445
> simulation(100000)
[1] 0.24923

Why i can't get the result 0.3?

Upvotes: 0

Views: 143

Answers (1)

Dason
Dason

Reputation: 62003

If all you want to do is get a discrete uniform distribution on the numbers 0, 1, ..., 9 then just use sample

sample(0:9, k, replace = TRUE)

With the code you have right now you'll actually get a probability of .05 each of getting 0 or 10 and a probability of .10 each of getting 1-9.

Upvotes: 8

Related Questions