Count frequency of occurrences including zeroes

Asked

Viewed 36 times

3

For the following case the x count using the function table will return the frequency of the existing values. I would like to know how to return the count to the discrete interval from 1 to 12, including the values whose frequency is zero.

set.seed(2)
x <- sample.int(12, 50, replace = TRUE)
table(x)

2 answers

4


To include the values for which the frequency is zero, convert to factor with all levels and apply table.

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

The value 10 has a frequency of zero but is in the final result, as requested.

  • This solution meets the problem. Thank you very much.

2

table uses the function tabulate, which returns all ranges by default. You can use it directly:

set.seed(2)
x <- sample(12, 20, replace = TRUE)

table(x)
#> x
#>  1  2  3  5  6  7  9 10 11 12
#>  1  1  5  1  2  3  1  1  2  3

tabulate(x)
#>  [1] 1 1 5 0 1 2 3 0 1 1 2 3

If you need it to return as a named vector:

setNames(tabulate(x), seq_len(max(x)))
#>  1  2  3  4  5  6  7  8  9 10 11 12
#>  1  1  5  0  1  2  3  0  1  1  2  3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.