DataTx
DataTx

Reputation: 1869

How to bin frequency above and below a value

There are quite a few question on binning in R but I have not come across this particular problem. I have a list of numbers and want to bin the frequency <=2 and >2.

To clarify I need a histogram with two bins composed of values <=2 and >2.

My variable is

Var = a
 [1] 2 2 1 0 1 1 1 1 1 3 2 3 3 5 1 4 4 0 3 4 1 0 3 3 0 0 1 3 2 6 2 2 2 1
[35] 0 2 3 2 0 0 0 0 3 2 2 4 3 2 2 0 4 1 0 1 3 1 4 3 1 2 6 7 6 1 2 2 4 5
[69] 3 0 6 5 2 0 7 1 7 3 1 4 1 1 2 1 1 2 1 1 4 2 0 3 3 2 2 2 5 3 2 5 2 5

I can organize into the numbers into a table to see the frequency of each number

a = table(var)

        Var1     Freq
    1   0     15
    2   1     23
    3   2     25
    4   3     17
    5   4     9
    6   5     6
    7   6     4
    8   7     3

Now how do I bin for values <=2 and >2?

Upvotes: 0

Views: 283

Answers (2)

alko989
alko989

Reputation: 7908

You can do:

ct  <- cut(a, breaks = c(0, 2, max(a)), include.lowest=TRUE, labels=c("<=2", ">2"))
## [1] <=2 <=2 <=2 <=2 <=2 <=2 <=2 <=2 <=2 >2  <=2 >2  >2  >2  <=2 >2  >2  <=2
## [19] >2  >2  <=2 <=2 >2  >2  <=2 <=2 <=2 >2  <=2 >2  <=2 <=2 <=2 <=2 <=2 <=2
## [37] >2  <=2 <=2 <=2 <=2 <=2 >2  <=2 <=2 >2  >2  <=2 <=2 <=2 >2  <=2 <=2 <=2
## [55] >2  <=2 >2  >2  <=2 <=2 >2  >2  >2  <=2 <=2 <=2 >2  >2  >2  <=2 >2  >2 
## [73] <=2 <=2 >2  <=2 >2  >2  <=2 >2  <=2 <=2 <=2 <=2 <=2 <=2 <=2 <=2 >2  <=2
## [91] <=2 >2  >2  <=2 <=2 <=2 >2  >2  <=2 >2  <=2 >2 
## Levels: <=2 >2

table(ct)
## ct
## <=2  >2 
## 63   39

You can plot it using barplot as @user20650 suggested:

barplot(table(ct))

enter image description here

Upvotes: 2

user20650
user20650

Reputation: 25844

As you are splitting your vector in two, you can create the groups by applying the inequality statements directly to the vector. To plot the table you can use barplot .

set.seed(1)     
var <- sample(1:10, 100, T)

(tab <- table(var<=2))
#FALSE  TRUE 
#   87    13 

barplot(tab)

Or directly

barplot(table(var<=2))

For more categories, the vector can be categorised using cut

Upvotes: 1

Related Questions