Question

I am using the cut() function to bin a vector integergers. The procedure works well and provides the number of integers that fall into each bin, however for bins without a number, it isn't listed. I would like to fill these in such that there is a cell for each bin and for bins without numbers, it fills them in with 0. For example:

set.seed(123)
x <- sample(1:3, 100, replace = TRUE) 
bins <- cut(x, breaks = 4, labels =FALSE)
bins_tab <- table(bins)
bins_tab

This gives:

bins
 1  3  4 
33 34 33

I would like to fill in 2 with a 0 such that the output is:

 bins
 1  2  3  4 
33  0 34 33

Any and all help appreciated.

Was it helpful?

Solution

Like this?

table( cut( x , breaks = 4 , labels = 1:4 ) )

# 1  2  3  4 
#33  0 34 33 

i.e. make sure there is a label for the empty factor level.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top