2

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.

4

1 回答 1

5

像这样?

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

# 1  2  3  4 
#33  0 34 33 

即确保有一个空因子级别的标签。

于 2013-10-28T16:36:17.983 回答