rprobabilityfrequencyprobability-densityfrequency-distribution

R: relative frequency in a table


I am working with quantil binomial and runif functions with R to simulate values.

My goal is get relative frequency with this function. The frequency that I get are ok, but the the relative frequency are wrong, example:

Edit: I forgot add set.seed, but in my task I put in my script

set.seed(123)

table(qbinom(runif(1000,0,1),6,0.2))

Frequencies:

 0   1   2   3   4   5 
277 367 245  88  22   1 

#Relative Frequencies ???? wrong???

table(qbinom(runif(1000,0,1),6,0.2))/1000

  0     1     2     3     4     5     6 
0.271 0.402 0.239 0.071 0.014 0.002 0.001 

My expected results are

  0      1      2     3     4       5 
0.277 0.367 0.245 0.088  0.022   0.001 

I am ok? Thanks


Solution

  • runif is a random function, every time you run it you will get a different value. You are very unlikely to get the same value twice when you run table(qbinom(runif(1000,0,1),6,0.2)) twice. For example if I run this a few times I get

    table(qbinom(runif(1000,0,1),6,0.2))
    #   0   1   2   3   4   5 
    # 260 390 250  87  12   1 
    
    table(qbinom(runif(1000,0,1),6,0.2))
    #   0   1   2   3   4   5 
    # 297 367 239  78  17   2 
    
    table(qbinom(runif(1000,0,1),6,0.2))
    #   0   1   2   3   4   5 
    # 263 395 243  81  17   1 
    

    Dividing by 1000 will give relative frequencies for a particular instance.

    If you want to get the same values, you could set your random seed before you call runif. For example

    set.seed(616)
    table(qbinom(runif(1000,0,1),6,0.2))
    #   0   1   2   3   4   5 
    # 270 383 248  76  22   1 
    
    set.seed(616)
    table(qbinom(runif(1000,0,1),6,0.2))
    #   0   1   2   3   4   5 
    # 270 383 248  76  22   1 
    
    set.seed(616)
    table(qbinom(runif(1000,0,1),6,0.2))/1000
    #     0     1     2     3     4     5 
    # 0.270 0.383 0.248 0.076 0.022 0.001 
    

    Or just save your random values

    set.seed(616)
    rand_vals <- runif(1000,0,1)
    table(qbinom(rand_vals,6,0.2))
    #   0   1   2   3   4   5 
    # 270 383 248  76  22   1 
    
    table(qbinom(rand_vals,6,0.2))/1000
    #     0     1     2     3     4     5 
    # 0.270 0.383 0.248 0.076 0.022 0.001