+4 votes
in Programming Languages by (5.2k points)
I have a vector of probabilities and want to divide it into 100 bins. How can I find the number of elements in each bin i.e bin frequency?

1 Answer

0 votes
by (33.0k points)

There are multiple ways. You can use either hist() or cut() function to divide your vector of probabilities into multiple bins and then find the bin frequency, i.e., the number of elements in each bin.

Here I am generating 500 random float values between 0 and 1 and dividing them into 10 bins.

Approach 1

> probs <- runif(500, 0, 1)
> g=as.data.frame(table(cut(probs, breaks=seq(0,1,0.1))))
> g
        Var1 Freq
1    (0,0.1]   58
2  (0.1,0.2]   37
3  (0.2,0.3]   44
4  (0.3,0.4]   57
5  (0.4,0.5]   59
6  (0.5,0.6]   48
7  (0.6,0.7]   53
8  (0.7,0.8]   43
9  (0.8,0.9]   50
10   (0.9,1]   51

> g$Freq
 [1] 58 37 44 57 59 48 53 43 50 51

Approach 2

> g1=hist(probs, breaks = 10, plot = FALSE)
> g1$counts
 [1] 58 37 44 57 59 48 53 43 50 51
>

...