Search code examples
rfrequency

R frequency tables using a sequence over a collection


I have this collection

x <- c(3,4,5,7,7,9,9,9,10,10,10,10,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,15,15)

And I want to get the frequencies of each value of the sequence 3:15 within that collection. If I do table(x) it gives me the frequencies of the existing values, but for example, the value 6 would have a frequency value of 0 and is not shown with table().


Solution

  • Use factor with levels in table.

    table(factor(x, levels = 3:15))
    
    # 3  4  5  6  7  8  9 10 11 12 13 14 15 
    # 1  1  1  0  2  0  3  4  7 10 14  3  2 
    

    Or for a general case :

    table(factor(x, levels = min(x):max(x)))