A more complicated way using sqldf :
First, we create a table that defines the cells and ranges (min and max):
bins <- data.frame(id = c(1, 2, 3, 4), bins = c("(0,5]", "(5,10]", "(10,15]", "(15,20]"), min = c(0, 6, 11, 16), max = c(5, 10, 15, 20)) id bins min max 1 1 (0,5] 0 5 2 2 (5,10] 6 10 3 3 (10,15] 11 15 4 4 (15,20] 16 20
Then we use the following query, using both tables, so that each bin sl in its corresponding group uses BETWEEN for those Value that are 0.
library(sqldf) sqldf("SELECT bins, COUNT(Value) AS freq FROM df, bins WHERE (((sl) BETWEEN [min] AND [max]) AND Value = 0) GROUP BY bins ORDER BY id")
Output:
bins freq 1 (0,5] 1 2 (5,10] 2 3 (10,15] 2 4 (15,20] 1
Another alternative to simplifying the design of the bins proposed by mts using cut is to extract levels factor:
bins <- data.frame(id = 1:4, bins = levels(cut(Sl, breaks = seq(0, 20, 5))), min = seq(1, 20, 5), max = seq(5, 20, 5))